Advertisement
Guest User

Untitled

a guest
Apr 7th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.70 KB | None | 0 0
  1. from django.db import models
  2. from django.contrib.auth.models import (
  3. BaseUserManager, AbstractBaseUser
  4. )
  5.  
  6. class AppCodeUserManager(BaseUserManager):
  7. def create_user(self, email, appcode, password=None):
  8. """
  9. Creates and saves a User with the given email, appcode and password.
  10. """
  11. if not email:
  12. raise ValueError('Users must have an email address')
  13.  
  14. user = self.model(
  15. email=self.normalize_email(email),
  16. appcodes=appcode
  17. )
  18.  
  19. user.set_password(password)
  20. user.save(using=self._db)
  21. return user
  22.  
  23. def create_superuser(self, email, appcode, password):
  24. """
  25. Creates and saves a superuser with the given email, appcode and password.
  26. """
  27. print("Creating superuser...")
  28. user = self.create_user(email,
  29. password=password,
  30. appcodes=appcode
  31. )
  32. user.is_admin = True
  33. user.save(using=self._db)
  34. return user
  35.  
  36. class AppCode(models.Model):
  37. appcode = models.CharField(max_length=255,unique=True)
  38.  
  39. def get_appcode(self):
  40. return self.appcode
  41.  
  42. class AppCodeUser(AbstractBaseUser):
  43. email = models.EmailField(
  44. verbose_name='email address',
  45. max_length=255,
  46. unique=True,
  47. )
  48. appcodes = models.ManyToManyField(AppCode)
  49. is_active = models.BooleanField(default=True)
  50. is_admin = models.BooleanField(default=False)
  51.  
  52. objects = AppCodeUserManager()
  53.  
  54. USERNAME_FIELD = 'email'
  55. REQUIRED_FIELDS = ['appcodes']
  56.  
  57. def get_appcodes(self):
  58. return "n".join([p.appcode for p in self.appcodes.all()])
  59.  
  60. def get_full_name(self):
  61. # The user is identified by their email address
  62. return self.email
  63.  
  64. def get_short_name(self):
  65. # The user is identified by their email address
  66. return self.email
  67.  
  68. def __str__(self): # __unicode__ on Python 2
  69. return self.email
  70.  
  71. def has_perm(self, perm, obj=None):
  72. "Does the user have a specific permission?"
  73. # Simplest possible answer: Yes, always
  74. return True
  75.  
  76. def has_module_perms(self, app_label):
  77. "Does the user have permissions to view the app `app_label`?"
  78. # Simplest possible answer: Yes, always
  79. return True
  80.  
  81. @property
  82. def is_staff(self):
  83. "Is the user a member of staff?"
  84. # Simplest possible answer: All admins are staff
  85. return self.is_admin
  86.  
  87. from django import forms
  88. from django.contrib import admin
  89. from django.contrib.auth.models import Group
  90. from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
  91. from django.contrib.auth.forms import ReadOnlyPasswordHashField
  92.  
  93. from models import AppCodeUser
  94.  
  95.  
  96. class UserCreationForm(forms.ModelForm):
  97. """A form for creating new users. Includes all the required
  98. fields, plus a repeated password."""
  99. password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
  100. password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
  101.  
  102. class Meta:
  103. model = AppCodeUser
  104. fields = ('email', 'appcodes')
  105.  
  106. def clean_password2(self):
  107. # Check that the two password entries match
  108. password1 = self.cleaned_data.get("password1")
  109. password2 = self.cleaned_data.get("password2")
  110. if password1 and password2 and password1 != password2:
  111. raise forms.ValidationError("Passwords don't match")
  112. return password2
  113.  
  114. def save(self, commit=True):
  115. # Save the provided password in hashed format
  116. user = super(UserCreationForm, self).save(commit=False)
  117. user.set_password(self.cleaned_data["password1"])
  118. if commit:
  119. user.save()
  120. return user
  121.  
  122.  
  123. class UserChangeForm(forms.ModelForm):
  124. """A form for updating users. Includes all the fields on
  125. the user, but replaces the password field with admin's
  126. password hash display field.
  127. """
  128. password = ReadOnlyPasswordHashField()
  129.  
  130. class Meta:
  131. model = AppCodeUser
  132. fields = ('email', 'password', 'appcodes', 'is_active', 'is_admin')
  133.  
  134. def clean_password(self):
  135. # Regardless of what the user provides, return the initial value.
  136. # This is done here, rather than on the field, because the
  137. # field does not have access to the initial value
  138. return self.initial["password"]
  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', 'is_admin', 'get_appcodes')
  150. list_filter = ('is_admin',)
  151. fieldsets = (
  152. (None, {'fields': ('email', 'password')}),
  153. ('Appcode info', {'fields': ('get_appcodes',)}),
  154. ('Permissions', {'fields': ('is_admin',)}),
  155. )
  156. # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
  157. # overrides get_fieldsets to use this attribute when creating a user.
  158. add_fieldsets = (
  159. (None, {
  160. 'classes': ('wide',),
  161. 'fields': ('email', 'get_appcodes', 'password1', 'password2')}
  162. ),
  163. )
  164. search_fields = ('email',)
  165. ordering = ('email',)
  166. filter_horizontal = ()
  167.  
  168. # Now register the new UserAdmin...
  169. admin.site.register(AppCodeUser, UserAdmin)
  170. # ... and, since we're not using Django's built-in permissions,
  171. # unregister the Group model from admin.
  172. admin.site.unregister(Group)
  173.  
  174. python manage.py createsuperuser
  175. Email address: asd@we.com
  176. Traceback (most recent call last):
  177. File "manage.py", line 10, in <module>
  178. execute_from_command_line(sys.argv)
  179. File "C:qweasdAppDataLocalContinuumAnaconda2libsite-packagesdjangocoremanagement__init__.py", line 353, in execute_from_command_line
  180. utility.execute()
  181. File "C:qweasdAppDataLocalContinuumAnaconda2libsite-packagesdjangocoremanagement__init__.py", line 345, in execute
  182. self.fetch_command(subcommand).run_from_argv(self.argv)
  183. File "C:qweasdAppDataLocalContinuumAnaconda2libsite-packagesdjangocoremanagementbase.py", line 348, in run_from_argv
  184. self.execute(*args, **cmd_options)
  185. File "C:qweasdAppDataLocalContinuumAnaconda2libsite-packagesdjangocontribauthmanagementcommandscreatesuperuser.py", line 52, in execute
  186. return super(Command, self).execute(*args, **options)
  187. File "C:qweasdAppDataLocalContinuumAnaconda2libsite-packagesdjangocoremanagementbase.py", line 399, in execute
  188. output = self.handle(*args, **options)
  189. File "C:qweasdAppDataLocalContinuumAnaconda2libsite-packagesdjangocontribauthmanagementcommandscreatesuperuser.py", line 127, in handle
  190. ) if field.remote_field else '',
  191. AttributeError: 'ManyToManyRel' object has no attribute 'field_name'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement