Advertisement
Guest User

Untitled

a guest
Aug 13th, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.64 KB | None | 0 0
  1. from django.shortcuts import render,redirect
  2. from django.views.generic import View
  3. from .forms import UserCreationForm,SignInForm
  4. from django.contrib.auth import login,logout,get_backends,authenticate
  5. from django.contrib.auth.decorators import login_required
  6. from django.utils.decorators import method_decorator
  7. from .backend import ClientAuthBackend
  8. from .models import MyUser
  9.  
  10. @login_required(login_url='/accounts/signin/')
  11. class 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.  
  17. class SignOutView(View):
  18.  
  19. def get(self,request):
  20. logout(request)
  21. return redirect(to='/accounts/signin/')
  22.  
  23. class 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.  
  44. class 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.  
  63. from django.conf.urls import url,include
  64. from django.contrib import admin
  65. from .views import SignUpView,SignInView,SignOutView,UserHomeView
  66.  
  67. urlpatterns = [
  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. """
  75. Django settings for django_3 project.
  76.  
  77. Generated by 'django-admin startproject' using Django 1.9.8.
  78.  
  79. For more information on this file, see
  80. https://docs.djangoproject.com/en/1.9/topics/settings/
  81.  
  82. For the full list of settings and their values, see
  83. https://docs.djangoproject.com/en/1.9/ref/settings/
  84. """
  85.  
  86. import os
  87.  
  88. # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
  89. BASE_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!
  96. SECRET_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!
  99. DEBUG = True
  100.  
  101. ALLOWED_HOSTS = []
  102.  
  103. STATIC_URL = '/static/'
  104. STATIC_ROOT = '/Users/waqarahmed/Desktop/Python Projects/learning_django/django_3/assets'
  105.  
  106. STATICFILES_DIRS = (
  107. os.path.join(
  108. BASE_DIR,'static',
  109. ),
  110. )
  111.  
  112. AUTH_USER_MODEL = 'users.MyUser'
  113. AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend','users.backend.ClientAuthBackend')
  114.  
  115. # Application definition
  116.  
  117. INSTALLED_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.  
  127. MIDDLEWARE_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.  
  138. ROOT_URLCONF = 'django_3.urls'
  139.  
  140. TEMPLATES = [
  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.  
  157. WSGI_APPLICATION = 'django_3.wsgi.application'
  158.  
  159.  
  160. # Database
  161. # https://docs.djangoproject.com/en/1.9/ref/settings/#databases
  162.  
  163. DATABASES = {
  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.  
  174. AUTH_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.  
  193. LANGUAGE_CODE = 'en-us'
  194.  
  195. TIME_ZONE = 'UTC'
  196.  
  197. USE_I18N = True
  198.  
  199. USE_L10N = True
  200.  
  201. USE_TZ = True
  202.  
  203.  
  204. # Static files (CSS, JavaScript, Images)
  205. # https://docs.djangoproject.com/en/1.9/howto/static-files/
  206.  
  207. STATIC_URL = '/static/'
  208.  
  209. from .models import MyUser
  210. from django.contrib.auth.backends import ModelBackend
  211.  
  212.  
  213. class 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.  
  232. from django.db import models
  233. from django.contrib.auth.models import (
  234. BaseUserManager,AbstractBaseUser
  235. )
  236. import time
  237. from django.utils.dateparse import parse_date
  238.  
  239.  
  240. class 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.  
  277. class 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.  
  310. System check identified no issues (0 silenced).
  311. August 13, 2016 - 21:57:16
  312. Django version 1.9.8, using settings 'django_3.settings'
  313. Starting development server at http://127.0.0.1:8000/
  314. Quit the server with CONTROL-C.
  315. Not 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
  319. Internal Server Error: /accounts/admin2@outlook.com/
  320. Traceback (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):
  331. AttributeError: 'UserHomeView' object has no attribute 'user'
  332. [13/Aug/2016 21:57:29] "GET /accounts/admin2@outlook.com/ HTTP/1.1" 500 71008
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement