· 9 years ago · Aug 13, 2016, 10:06 PM
1from django.shortcuts import render,redirect
2from django.views.generic import View
3from .forms import UserCreationForm,SignInForm
4from django.contrib.auth import login,logout,get_backends,authenticate
5from django.contrib.auth.decorators import login_required
6from django.utils.decorators import method_decorator
7from .backend import ClientAuthBackend
8from .models import MyUser
9
10@login_required(login_url='/accounts/signin/')
11class UserHomeView(View):
12
13 def get(self,request,email):
14 print(request.user.is_authenticated())
15 return render(request,'user_home_view.html',{'title':'Home','user':MyUser.objects.get(email=email)})
16
17class SignOutView(View):
18
19 def get(self,request):
20 logout(request)
21 return redirect(to='/accounts/signin/')
22
23class SignInView(View):
24
25 def get(self,request):
26 return render(request,'log_in.html',{'title':'Sign In','form':SignInForm()})
27
28 def post(self,request):
29 form = SignInForm(request.POST)
30 if form.is_valid():
31 email = form.cleaned_data['email']
32 password = form.cleaned_data['password']
33 user = authenticate(username=email,password=password)
34 if user is not None:
35 login(request,user)
36 return redirect(to='/accounts/' + str(email) + '/')
37 else:
38 form.add_error(None,"Couldn't authenticate your credentials !")
39 return render(request,'log_in.html',{'title':'Sign In','form':form})
40 else:
41 return render(request, 'log_in.html', {'title': 'Sign In', 'form': form})
42
43
44class SignUpView(View):
45
46 def get(self,request):
47 return render(request,'sign_up.html',{'title':'Sign Up','form':UserCreationForm()})
48
49 def post(self,request):
50 form = UserCreationForm(request.POST)
51 try:
52 if form.is_valid():
53 user = MyUser.objects.create_user(email=form.cleaned_data['email'],date_of_birth=
54 form.cleaned_data['date_of_birth'],first_name=form.cleaned_data['first_name'],last_name=
55 form.cleaned_data['last_name'],password=form.clean_password2())
56 return redirect(to='/accounts/signin')
57 else:
58 return render(request,'sign_up.html',{'title':'Sign Up','form':form})
59 except ValueError:
60 form.add_error(None,"Passwords don't match !!!")
61 return render(request, 'sign_up.html', {'title': 'Sign Up', 'form': form})
62
63from django.conf.urls import url,include
64from django.contrib import admin
65from .views import SignUpView,SignInView,SignOutView,UserHomeView
66
67urlpatterns = [
68 url(r'^signup/$',SignUpView.as_view()),
69 url(r'^signin/$',SignInView.as_view()),
70 url(r'^signout/$',SignOutView.as_view()),
71 url(r'^(?P<email>[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+)/',UserHomeView.as_view()),
72]
73
74"""
75Django settings for django_3 project.
76
77Generated by 'django-admin startproject' using Django 1.9.8.
78
79For more information on this file, see
80https://docs.djangoproject.com/en/1.9/topics/settings/
81
82For the full list of settings and their values, see
83https://docs.djangoproject.com/en/1.9/ref/settings/
84"""
85
86import os
87
88# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
89BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
90
91
92# Quick-start development settings - unsuitable for production
93# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
94
95# SECURITY WARNING: keep the secret key used in production secret!
96SECRET_KEY = 'ac=6)v&jf(90%!op*$ttf29+qw_51n+(5#(jas&f&*(!=q310u'
97
98# SECURITY WARNING: don't run with debug turned on in production!
99DEBUG = True
100
101ALLOWED_HOSTS = []
102
103STATIC_URL = '/static/'
104STATIC_ROOT = '/Users/waqarahmed/Desktop/Python Projects/learning_django/django_3/assets'
105
106STATICFILES_DIRS = (
107 os.path.join(
108 BASE_DIR,'static',
109 ),
110)
111
112AUTH_USER_MODEL = 'users.MyUser'
113AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend','users.backend.ClientAuthBackend')
114
115# Application definition
116
117INSTALLED_APPS = [
118 'django.contrib.admin',
119 'django.contrib.auth',
120 'django.contrib.contenttypes',
121 'django.contrib.sessions',
122 'django.contrib.messages',
123 'django.contrib.staticfiles',
124 'users',
125]
126
127MIDDLEWARE_CLASSES = [
128 'django.middleware.security.SecurityMiddleware',
129 'django.contrib.sessions.middleware.SessionMiddleware',
130 'django.middleware.common.CommonMiddleware',
131 'django.middleware.csrf.CsrfViewMiddleware',
132 'django.contrib.auth.middleware.AuthenticationMiddleware',
133 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
134 'django.contrib.messages.middleware.MessageMiddleware',
135 'django.middleware.clickjacking.XFrameOptionsMiddleware',
136]
137
138ROOT_URLCONF = 'django_3.urls'
139
140TEMPLATES = [
141 {
142 'BACKEND': 'django.template.backends.django.DjangoTemplates',
143 'DIRS': [os.path.join(BASE_DIR, 'templates')]
144 ,
145 'APP_DIRS': True,
146 'OPTIONS': {
147 'context_processors': [
148 'django.template.context_processors.debug',
149 'django.template.context_processors.request',
150 'django.contrib.auth.context_processors.auth',
151 'django.contrib.messages.context_processors.messages',
152 ],
153 },
154 },
155]
156
157WSGI_APPLICATION = 'django_3.wsgi.application'
158
159
160# Database
161# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
162
163DATABASES = {
164 'default': {
165 'ENGINE': 'django.db.backends.sqlite3',
166 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
167 }
168}
169
170
171# Password validation
172# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
173
174AUTH_PASSWORD_VALIDATORS = [
175 {
176 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
177 },
178 {
179 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
180 },
181 {
182 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
183 },
184 {
185 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
186 },
187]
188
189
190# Internationalization
191# https://docs.djangoproject.com/en/1.9/topics/i18n/
192
193LANGUAGE_CODE = 'en-us'
194
195TIME_ZONE = 'UTC'
196
197USE_I18N = True
198
199USE_L10N = True
200
201USE_TZ = True
202
203
204# Static files (CSS, JavaScript, Images)
205# https://docs.djangoproject.com/en/1.9/howto/static-files/
206
207STATIC_URL = '/static/'
208
209from .models import MyUser
210from django.contrib.auth.backends import ModelBackend
211
212
213class ClientAuthBackend(ModelBackend):
214
215 def authenticate(self,username=None,password=None):
216 try:
217 user = MyUser.objects.get(email=username)
218 if user.check_password(password):
219 return user
220 else:
221 return None
222 except MyUser.DoesNotExist:
223 return None
224
225 def get_user(self,email):
226 try:
227 user = MyUser.objects.get(email=email)
228 return user
229 except MyUser.DoesNotExist:
230 return None
231
232from django.db import models
233from django.contrib.auth.models import (
234 BaseUserManager,AbstractBaseUser
235)
236import time
237from django.utils.dateparse import parse_date
238
239
240class MyUserManager(BaseUserManager):
241 def create_user(self, email, date_of_birth, first_name, last_name, password=None):
242
243 if not email:
244 raise ValueError('User must have an email id !')
245 email = str(email).lower()
246 date_of_birth = str(date_of_birth)
247 user = self.model(
248 email = self.normalize_email(email=email),
249 date_of_birth = parse_date(date_of_birth),
250 first_name = first_name,
251 last_name = last_name,
252 join_date = time.strftime('%Y-%m-%d'),
253 )
254 user.set_password(password)
255 user.save()
256
257 return user
258
259 def create_superuser(self, email, date_of_birth, first_name, last_name, password=None):
260
261 if not email:
262 raise ValueError('User must have an email id !')
263
264 user = self.model(
265 email = self.normalize_email(email=email),
266 date_of_birth = date_of_birth,
267 first_name = first_name,
268 last_name = last_name,
269 join_date = time.strftime('%Y-%m-%d'),
270 )
271 user.is_admin = True
272 user.set_password(password)
273 user.save()
274
275 return user
276
277class MyUser(AbstractBaseUser):
278
279 email = models.EmailField(verbose_name='email address',max_length=255,unique=True)
280 first_name = models.CharField(max_length=255)
281 last_name = models.CharField(max_length=255)
282 join_date = models.DateField(auto_now_add=True)
283 date_of_birth = models.DateField()
284 is_active = models.BooleanField(default=True)
285 is_admin = models.BooleanField(default=False)
286
287 objects = MyUserManager()
288 USERNAME_FIELD = 'email'
289 REQUIRED_FIELDS = ['first_name','last_name','date_of_birth']
290
291 def get_full_name(self):
292 return self.email
293
294 def get_short_name(self):
295 return self.email
296
297 def __str__(self):
298 return self.email
299
300 def has_perm(self, perm, obj=None):
301 return True
302
303 def has_module_perms(self, app_label):
304 return True
305
306 @property
307 def is_staff(self):
308 return self.is_admin
309
310System check identified no issues (0 silenced).
311August 13, 2016 - 21:57:16
312Django version 1.9.8, using settings 'django_3.settings'
313Starting development server at http://127.0.0.1:8000/
314Quit the server with CONTROL-C.
315Not Found: /
316[13/Aug/2016 21:57:25] "GET / HTTP/1.1" 404 2015
317[13/Aug/2016 21:57:26] "GET /accounts/signup/ HTTP/1.1" 200 2916
318[13/Aug/2016 21:57:28] "GET /accounts/signup/ HTTP/1.1" 200 2916
319Internal Server Error: /accounts/admin2@outlook.com/
320Traceback (most recent call last):
321 File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
322 response = self.process_exception_by_middleware(e, request)
323 File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
324 response = wrapped_callback(request, *callback_args, **callback_kwargs)
325 File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
326 return self.dispatch(request, *args, **kwargs)
327 File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch
328 return handler(request, *args, **kwargs)
329 File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view
330 if test_func(request.user):
331AttributeError: 'UserHomeView' object has no attribute 'user'
332[13/Aug/2016 21:57:29] "GET /accounts/admin2@outlook.com/ HTTP/1.1" 500 71008