Advertisement
Guest User

Untitled

a guest
Jul 5th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.26 KB | None | 0 0
  1. ## ADMIN.PY ##
  2.  
  3.  
  4. from django.contrib import admin
  5. from django import forms
  6. from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
  7. from django.contrib.auth.forms import ReadOnlyPasswordHashField
  8. from django.contrib.auth.models import Group
  9.  
  10. from myApp.models import MyUser, RegularUser, AdminUser
  11.  
  12.  
  13. # Register your models here.
  14.  
  15.  
  16. class UserCreationForm(forms.ModelForm):
  17.     """A form for creating new users. Includes all the required fields,
  18.     plus a repeated password"""
  19.     password1 = forms.CharField(label='Contraseña', widget=forms.PasswordInput)
  20.     password2 = forms.CharField(label='Repita Contraseña',
  21.                                 widget=forms.PasswordInput)
  22.  
  23.     class Meta:
  24.         model = MyUser
  25.         fields = ('email',
  26.                   'first_name',
  27.                   'last_name',
  28.                   'telefono',
  29.                   'avatar',
  30.                   'groups',)
  31.  
  32.     def clean_password2(self):
  33.         # Check that the two password entries match
  34.         password1 = self.cleaned_data.get("password1")
  35.         password2 = self.cleaned_data.get("password2")
  36.         if password1 and password2 and password1 != password2:
  37.             raise forms.ValidationError("Las contraseñas no coinciden")
  38.         return password2
  39.  
  40.     def save(self, commit=True):
  41.         # Save the provided password in hashed format
  42.         user = super().save(commit=False)
  43.         user.set_password(self.cleaned_data["password1"])
  44.         if commit:
  45.             user.save()
  46.         return user
  47.  
  48.  
  49. class UserChangeForm(forms.ModelForm):
  50.     """A form for updating users. Includes all the fields on the user
  51.    , but replaces the password field with admin's password
  52.    hash display field"""
  53.  
  54.     password = ReadOnlyPasswordHashField()
  55.  
  56.     class Meta:
  57.         model = MyUser
  58.         fields = ('username',
  59.                   'email',
  60.                   'password',
  61.                   'first_name',
  62.                   'last_name',
  63.                   'descripcion',
  64.                   'telefono',
  65.                   'avatar',
  66.                   )
  67.  
  68.     def clean_password(self):
  69.         # Regardless of what the user provides, return the initial value.
  70.         # This is done here, rather than on the field, because the
  71.         # field does not have access to the initial value
  72.         return self.initial["password"]
  73.  
  74.  
  75. class AdminCreationForm(forms.ModelForm):
  76.     """A form for creating new Admin users. Including all required fields,
  77.    plus a repeated password"""
  78.     password1 = forms.CharField(label='Contraseña', widget=forms.PasswordInput)
  79.     password2 = forms.CharField(label='Repita Contraseña', widget=forms.PasswordInput)
  80.  
  81.     # usuarios = forms.CharField(label= 'Usuarios', widget=forms.SelectMultiple(choices=RegularUser.objects.all()))
  82.  
  83.     class Meta:
  84.         model = AdminUser
  85.         fields = ('username',
  86.                   'email',
  87.                   'password',
  88.                   'telefono',
  89.                   'avatar',
  90.                   'usuarios',)
  91.  
  92.     def clean_password2(self):
  93.         # Check that the 2 password entries match
  94.         password1 = self.cleaned_data.get('password1')
  95.         password2 = self.cleaned_data.get('password2')
  96.         if password1 and password2 and password1 != password2:
  97.             raise ValueError("Las contraseñas no coinciden")
  98.         return password2
  99.  
  100.     def save(self, commit=True):
  101.         # Save the commit password in hashed form
  102.         user = super().save(commit=False)
  103.         user.set_password(self.cleaned_data['password1'])
  104.         # Set the current User as admin user
  105.         user.is_staff = True
  106.  
  107.         if commit:
  108.             user.save()
  109.             group = Group.objects.get(name="Administrators")
  110.             group.user_set.add(user)
  111.             group.save()
  112.         return user
  113.  
  114.  
  115. class AdminChangeForm(forms.ModelForm):
  116.     """ A form for updating Administrators. Includes all the fields on the user
  117.    , but replaces the password field with admin's password hash display field"""
  118.  
  119.     password = ReadOnlyPasswordHashField()
  120.  
  121.     class Meta:
  122.         model = AdminUser
  123.         fields = ('username',
  124.                   'email',
  125.                   'password',
  126.                   'first_name',
  127.                   'last_name',
  128.                   'descripcion',
  129.                   'telefono',
  130.                   'avatar',
  131.                   'usuarios',
  132.                   'groups',
  133.                   )
  134.  
  135.     def clean_password(self):
  136.         # Regardless of what the admin provides, return the initial value.
  137.         # This is done here, rather than on the field, because the
  138.         # field does not have access to the initial value
  139.         return self.initial["password"]
  140.  
  141.  
  142. class AdminUserAdmin(BaseUserAdmin):
  143.     # The forms to add and change admin instances
  144.     form = AdminChangeForm
  145.     add_form = AdminCreationForm
  146.  
  147.     # The fields to be used in displaying the Admin model.
  148.     # These overrides the definitions on the base AdminUserAdmin
  149.     # that reference specific fields on auth.User
  150.     list_display = ('username', 'email',)
  151.     list_filter = ('last_login',)
  152.     fieldsets = (
  153.         (None, {'fields': ('email', 'password')}),
  154.         ('Información Personal', {'fields': ('first_name', 'last_name', 'descripcion', 'avatar', 'telefono',)}),
  155.         ('Administración', {'fields': ('is_staff', 'usuarios',)}),
  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': ('username', 'email', 'telefono', 'password1', 'password2', 'usuarios',)}
  163.          ),
  164.     )
  165.     search_fields = ('username',)
  166.     ordering = ('username',)
  167.     filter_horizontal = ()
  168.  
  169.  
  170. class UserAdmin(BaseUserAdmin):
  171.     # The forms to add and change user instances
  172.     form = UserChangeForm
  173.     add_form = UserCreationForm
  174.  
  175.     # The fields to be used in displaying the User model.
  176.     # These override the definitions on the base UserAdmin
  177.     # that reference specific fields on auth.User.
  178.     list_display = ('username', 'email', 'is_staff')
  179.     list_filter = ('is_staff',)
  180.     fieldsets = (
  181.         (None, {'fields': ('email', 'password')}),
  182.         ('Personal info', {'fields': ('first_name', 'last_name', 'descripcion', 'avatar', 'telefono',)}),
  183.         ('Permissions', {'fields': ('is_staff', 'is_superuser')}),
  184.     )
  185.     # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
  186.     # overrides get_fieldsets to use this attribute when creating a user.
  187.     add_fieldsets = (
  188.         (None, {
  189.             'classes': ('wide',),
  190.             'fields': ('username', 'email', 'telefono', 'password1', 'password2',)}
  191.          ),
  192.     )
  193.     search_fields = ('username',)
  194.     ordering = ('username',)
  195.     filter_horizontal = ()
  196.  
  197.     # Now register the new UserAdmin...
  198.  
  199.  
  200. admin.site.register(MyUser, UserAdmin)
  201.  
  202. admin.site.register(AdminUser, AdminUserAdmin)
  203.  
  204.  
  205. # @admin.register(MyUser)
  206. # class MyUserAdmin(admin.ModelAdmin):
  207. #     pass
  208.  
  209.  
  210. # @admin.register(AdminUser)
  211. # class AdminUserAdmin(admin.ModelAdmin):
  212. #     # The forms to add and change Admin instances:
  213. #     form = AdminChangeForm
  214.  
  215.  
  216. @admin.register(RegularUser)
  217. class RegularUserAdmin(admin.ModelAdmin):
  218.     pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement