Advertisement
Guest User

Untitled

a guest
Jul 2nd, 2016
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.55 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. u"""Classes for extended Django user model."""
  4.  
  5. from django.contrib.auth.models import AbstractBaseUser
  6. from django.contrib.auth.models import BaseUserManager
  7. from django.contrib.auth.models import PermissionsMixin
  8. from django.db import models
  9.  
  10.  
  11. class UserManager(BaseUserManager):
  12.  
  13. u"""Default class for models managing."""
  14.  
  15. def create_user(self, email, password=None):
  16. u"""
  17. Create ExtUser. Email (default) is required.
  18. You can override required field here and in ExtUser model.
  19. """
  20. if not email:
  21. raise ValueError('Email is required.')
  22.  
  23. user = self.model(
  24. email=UserManager.normalize_email(email),
  25. )
  26.  
  27. user.set_password(password)
  28. user.save(using=self._db)
  29. return user
  30.  
  31. def create_superuser(self, email, password):
  32. u"""Create superuser."""
  33. user = self.create_user(email, password)
  34. user.is_admin = True
  35. user.is_superuser = True
  36. user.save(using=self._db)
  37. return user
  38.  
  39.  
  40. class ExtUser(AbstractBaseUser, PermissionsMixin):
  41. u"""
  42. Default ExtUser model for replacing default User model.
  43. You must make all changes, definition additional fields and other here.
  44. """
  45. email = models.EmailField(
  46. 'Email',
  47. max_length=255,
  48. unique=True,
  49. db_index=True
  50. )
  51. username = models.CharField(
  52. 'First name',
  53. max_length=40,
  54. null=True,
  55. blank=True
  56. )
  57. register_date = models.DateField(
  58. 'Registration date',
  59. auto_now_add=True
  60. )
  61. is_active = models.BooleanField(
  62. 'Active', # Not blocked, banned, etc
  63. default=True
  64. )
  65. is_admin = models.BooleanField(
  66. 'Is superuser',
  67. default=False
  68. )
  69.  
  70. # Django require define this method
  71. def get_full_name(self):
  72. return self.email
  73.  
  74. @property
  75. def is_staff(self):
  76. # Required Django for admin panel
  77. return self.is_admin
  78.  
  79. def get_short_name(self):
  80. u"""Return short name."""
  81. return self.email
  82.  
  83. def __str__(self):
  84. u"""String representation of model. Email by default."""
  85. return self.email
  86.  
  87. # Field, used as 'username' in authentication and other forms
  88. USERNAME_FIELD = 'email'
  89.  
  90. """
  91. Username required by default. Add here another fields, where
  92. must be defined for correct model creation.
  93. """
  94. REQUIRED_FIELDS = []
  95.  
  96. # Link model and model manager
  97. objects = UserManager()
  98.  
  99. class Meta:
  100. verbose_name = 'user'
  101. verbose_name_plural = 'users'
  102. db_table = 'extuser'
  103.  
  104. u"""Used in admin panel and for initialization."""
  105. from django.contrib import admin
  106. from django.contrib.auth.admin import UserAdmin
  107. from django.contrib.auth.models import Group
  108.  
  109. from .forms import UserChangeForm
  110. from .forms import UserCreationForm
  111. from .models import ExtUser
  112.  
  113.  
  114. class UserAdmin(UserAdmin):
  115. """
  116. Base admin class.
  117. form - form for change user settings.
  118. add_form - used for create users
  119. """
  120. form = UserChangeForm
  121. add_form = UserCreationForm
  122.  
  123. # Fields listed in admin panel
  124. list_display = [
  125. 'email',
  126. 'username',
  127. 'is_admin',
  128. ]
  129.  
  130. # Filter for admin panel
  131. list_filter = ('is_admin',)
  132.  
  133. # Fieldsets for ordering and grouping
  134. fieldsets = (
  135. (None, {'fields': ('email', 'password', 'username')}),
  136. ('Permissions', {'fields': ('is_admin',)}),
  137. ('Important dates', {'fields': ('last_login',)}),
  138. )
  139.  
  140. add_fieldsets = (
  141. (None, {
  142. 'classes': ('wide',),
  143. 'fields': (
  144. 'email',
  145. 'password1',
  146. 'password2'
  147. )}
  148. ),
  149. )
  150.  
  151. search_fields = ('email',)
  152. ordering = ('email',)
  153. filter_horizontal = ()
  154.  
  155. # Register ExtUser admin panel in Django
  156. admin.site.register(ExtUser, UserAdmin)
  157. admin.site.unregister(Group)
  158.  
  159. from django import forms
  160. from django.contrib.auth.forms import ReadOnlyPasswordHashField
  161. from django.contrib.auth import get_user_model
  162.  
  163.  
  164. class UserCreationForm(forms.ModelForm):
  165. password1 = forms.CharField(
  166. label='Пароль',
  167. widget=forms.PasswordInput
  168. )
  169. password2 = forms.CharField(
  170. label='Подтверждение',
  171. widget=forms.PasswordInput
  172. )
  173.  
  174. def clean_password2(self):
  175. password1 = self.cleaned_data.get('password1')
  176. password2 = self.cleaned_data.get('password2')
  177. if password1 and password2 and password1 != password2:
  178. raise forms.ValidationError('Пароль и подтверждение не совпадают')
  179. return password2
  180.  
  181. def save(self, commit=True):
  182. user = super(UserCreationForm, self).save(commit=False)
  183. user.set_password(self.cleaned_data['password1'])
  184. if commit:
  185. user.save()
  186. return user
  187.  
  188. class Meta:
  189. model = get_user_model()
  190. fields = ('email',)
  191.  
  192.  
  193. class UserChangeForm(forms.ModelForm):
  194.  
  195.  
  196. password = ReadOnlyPasswordHashField(
  197. widget=forms.PasswordInput,
  198. required=False
  199. )
  200.  
  201. def save(self, commit=True):
  202. user = super(UserChangeForm, self).save(commit=False)
  203. password = self.cleaned_data["password"]
  204. if password:
  205. user.set_password(password)
  206. if commit:
  207. user.save()
  208. return user
  209.  
  210. class Meta:
  211. model = get_user_model()
  212. fields = ['email', ]
  213.  
  214.  
  215. class LoginForm(forms.Form):
  216.  
  217. """Форма для входа в систему
  218. """
  219. username = forms.CharField()
  220. password = forms.CharField()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement