Guest User

Untitled

a guest
Jun 17th, 2018
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.50 KB | None | 0 0
  1. python manage.py createsuperuser
  2.  
  3. AUTH_USER_MODEL = 'accounts.CustomUser'
  4.  
  5. from django.db import models
  6. from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
  7.  
  8.  
  9. class CustomUserManager(BaseUserManager):
  10.  
  11. def create_user(self, email, password):
  12.  
  13. if not email:
  14. raise ValueError("Users must have an email address")
  15. if not password:
  16. raise ValueError("Users must have a password")
  17.  
  18. user = self.model(
  19. email = self.normalize_email(email)
  20. )
  21.  
  22. user.set_password(password)
  23. user.save(using=self._db)
  24.  
  25. return user
  26.  
  27.  
  28. def create_staffuser(self, email, password, first_name, last_name):
  29.  
  30. if not first_name:
  31. raise ValueError("Staff and superusers must have a first name")
  32. if not last_name:
  33. raise ValueError("Staff and superusers must have a last name")
  34.  
  35. user = self.create_user(
  36. email,
  37. password=password
  38. )
  39.  
  40. user.first_name = first_name
  41. user.last_name = last_name
  42. user.is_staff = True
  43. user.save(using=self._db)
  44.  
  45. return user
  46.  
  47.  
  48. def create_superuser(self, email, password, first_name, last_name):
  49.  
  50. user = self.create_staffuser(
  51. email,
  52. password=password,
  53. first_name=first_name,
  54. last_name=last_name
  55. )
  56.  
  57. user.is_admin = True
  58. user.save(using=self._db)
  59.  
  60. return user
  61.  
  62.  
  63. class CustomUser(AbstractBaseUser, PermissionsMixin):
  64.  
  65. email = models.EmailField(null=True, max_length=80, unique=True)
  66. USERNAME_FIELD = 'email'
  67. is_active = models.BooleanField(default=True)
  68. is_admin = models.BooleanField(default=False)
  69. is_staff = models.BooleanField(default=False)
  70. first_name = models.CharField(max_length=25, blank=True, null=True)
  71. last_name = models.CharField(max_length=25, blank=True, null=True)
  72. date_joined = models.DateField(auto_now_add=True, null=True)
  73. REQUIRED_FIELDS = [first_name, last_name]
  74.  
  75. objects = CustomUserManager()
  76.  
  77. def __str__(self):
  78. return self.email
  79.  
  80. def get_short_name():
  81. return first_name
  82.  
  83. def get_full_name():
  84. return first_name + ' ' + last_name
  85.  
  86. from django import forms
  87. from django.contrib.auth.forms import ReadOnlyPasswordHashField
  88. from .models import CustomUser
  89.  
  90.  
  91. class UserCreationForm(forms.ModelForm):
  92. """A form for creating new users. Includes all the required
  93. fields, plus a repeated password."""
  94. password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
  95. password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
  96.  
  97. class Meta:
  98. model = CustomUser
  99. fields = ('email', 'first_name', 'last_name')
  100.  
  101. def clean_password2(self):
  102. # Check that the two password entries match
  103. password1 = self.cleaned_data.get("password1")
  104. password2 = self.cleaned_data.get("password2")
  105. if password1 and password2 and password1 != password2:
  106. raise forms.ValidationError("Passwords don't match")
  107. return password2
  108.  
  109. def save(self, commit=True):
  110. # Save the provided password in hashed format
  111. user = super().save(commit=False)
  112. user.set_password(self.cleaned_data["password1"])
  113. if commit:
  114. user.save()
  115. return user
  116.  
  117.  
  118. class UserChangeForm(forms.ModelForm):
  119. """A form for updating users. Includes all the fields on
  120. the user, but replaces the password field with admin's
  121. password hash display field.
  122. """
  123. password = ReadOnlyPasswordHashField()
  124.  
  125. class Meta:
  126. model = CustomUser
  127. fields = ('email', 'password', 'first_name', 'last_name', 'is_active', 'is_admin')
  128.  
  129. def clean_password(self):
  130. # Regardless of what the user provides, return the initial value.
  131. # This is done here, rather than on the field, because the
  132. # field does not have access to the initial value
  133. return self.initial["password"]
  134.  
  135. from django.contrib import admin
  136. from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
  137. from .models import CustomUser
  138. from .forms import UserCreationForm, UserChangeForm
  139.  
  140.  
  141. class UserAdmin(BaseUserAdmin):
  142. # The forms to add and change user instances
  143. form = UserChangeForm
  144. add_form = UserCreationForm
  145.  
  146. # The fields to be used in displaying the User model.
  147. # These override the definitions on the base UserAdmin
  148. # that reference specific fields on auth.User.
  149. list_display = ('email', 'first_name', 'last_name', 'is_admin')
  150. list_filter = ('is_admin',)
  151. fieldsets = (
  152. (None, {'fields': ('email', 'password')}),
  153. ('Personal info', {'fields': ('first_name', 'last_name',)}),
  154. ('Meta', {'fields': ('date_joined', 'last_login', 'is_active',)}),
  155. ('Permissions', {'fields': ('is_admin', 'is_staff',)}),
  156. )
  157. # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
  158. # overrides get_fieldsets to use this attribute when creating a user.
  159. add_fieldsets = (
  160. (None, {
  161. 'classes': ('wide',),
  162. 'fields': ('email', 'first_name', 'last_name' 'password1', 'password2')}
  163. ),
  164. )
  165. search_fields = ('email', 'first_name')
  166. ordering = ('email',)
  167. filter_horizontal = ()
  168.  
  169. admin.site.register(CustomUser, UserAdmin)
  170.  
  171. Traceback (most recent call last):
  172. File "manage.py", line 15, in <module>
  173. execute_from_command_line(sys.argv)
  174. File "/home/howdidthishappen/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
  175. utility.execute()
  176. File "/home/howdidthishappen/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
  177. self.fetch_command(subcommand).run_from_argv(self.argv)
  178. File "/home/howdidthishappen/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/base.py", line 282, in run_from_argv
  179. options = parser.parse_args(argv[2:])
  180. File "/home/howdidthishappen/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/base.py", line 54, in parse_args
  181. return super().parse_args(args, namespace)
  182. File "/usr/lib/python3.6/argparse.py", line 1739, in parse_args
  183. args, argv = self.parse_known_args(args, namespace)
  184. File "/usr/lib/python3.6/argparse.py", line 1760, in parse_known_args
  185. if not hasattr(namespace, action.dest):
  186. TypeError: hasattr(): attribute name must be string
Add Comment
Please, Sign In to add comment