Guest User

bino: MyAuth , admin.py

a guest
Feb 22nd, 2013
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.42 KB | None | 0 0
  1. from django import forms
  2. from django.contrib import admin
  3. from django.contrib.auth.forms import ReadOnlyPasswordHashField
  4. from django.utils.crypto import get_random_string
  5. from django.utils.encoding import smart_str
  6. from django.utils.translation import ugettext_lazy as _
  7. from django.utils import timezone
  8.  
  9. from myauth.models import Company, MyGroup, MyUser
  10.  
  11. class MyUserCreationForm(forms.ModelForm):
  12.     """
  13.    A form that creates a myuser, with no privileges, from the given username and
  14.    password.
  15.    """
  16.     error_messages = {
  17.         'duplicate_username': _("A user with that username already exists."),
  18.         'password_mismatch': _("The two password fields didn't match."),
  19.     }
  20.     company = forms.ModelChoiceField(queryset=Company.objects.all())
  21.     username = forms.RegexField(label=_("Username"), max_length=30,
  22.         regex=r'^[\w.@+-]+$',
  23.         help_text = _("Required. 30 characters or fewer. Letters, digits and "
  24.                       "@/./+/-/_ only."),
  25.         error_messages = {
  26.             'invalid': _("This value may contain only letters, numbers and "
  27.                          "@/./+/-/_ characters.")})
  28.     password1 = forms.CharField(label=_("Password"),
  29.         widget=forms.PasswordInput)
  30.     password2 = forms.CharField(label=_("Password confirmation"),
  31.         widget=forms.PasswordInput,
  32.         help_text = _("Enter the same password as above, for verification."))
  33.  
  34.     class Meta:
  35.         model = MyUser
  36.         fields = ("username",)
  37.  
  38.     def clean_username(self):
  39.         # Since MyUser.username is unique, this check is redundant,
  40.         # but it sets a nicer error message than the ORM. See #13147.
  41.         username = self.cleaned_data["username"]
  42.         try:
  43.             MyUser.objects.get(username=username, company=company)
  44.         except MyUser.DoesNotExist:
  45.             return username
  46.         raise forms.ValidationError(self.error_messages['duplicate_username'])
  47.  
  48.     def clean_password2(self):
  49.         password1 = self.cleaned_data.get("password1", "")
  50.         password2 = self.cleaned_data["password2"]
  51.         if password1 != password2:
  52.             raise forms.ValidationError(
  53.                 self.error_messages['password_mismatch'])
  54.         return password2
  55.  
  56.     def save(self, commit=True):
  57.         myuser = super(MyUserCreationForm, self).save(commit=False)
  58.         myuser.set_password(self.cleaned_data["password1"])
  59.         if commit:
  60.             myuser.save()
  61.         return user
  62.  
  63. class MyUserChangeForm(forms.ModelForm):
  64.     username = forms.RegexField(
  65.         label=_("Username"), max_length=30, regex=r"^[\w.@+-]+$",
  66.         help_text = _("Required. 30 characters or fewer. Letters, digits and "
  67.                       "@/./+/-/_ only."),
  68.         error_messages = {
  69.             'invalid': _("This value may contain only letters, numbers and "
  70.                          "@/./+/-/_ characters.")})
  71.     password = ReadOnlyPasswordHashField(label=_("Password"),
  72.         help_text=_("Raw passwords are not stored, so there is no way to see "
  73.                     "this user's password, but you can change the password "
  74.                     "using <a href=\"password/\">this form</a>."))
  75.     is_active= forms.BooleanField(label=_("Is Admin?"))
  76.     is_staff= forms.BooleanField(label=_("Is Staff?"))
  77.     is_admin= forms.BooleanField(label=_("Is Admin?"))
  78.  
  79.     def clean_password(self):
  80.         return self.initial["password"]
  81.  
  82.     class Meta:
  83.         model = MyUser
  84.  
  85.     def __init__(self, *args, **kwargs):
  86.         super(MyUserChangeForm, self).__init__(*args, **kwargs)
  87.         f = self.fields.get('user_permissions', None)
  88.         if f is not None:
  89.             f.queryset = f.queryset.select_related('content_type')
  90.  
  91.  
  92.  
  93. class MyUserAdmin(admin.ModelAdmin):
  94.     # The forms to add and change user instances
  95.     form = MyUserChangeForm
  96.     add_form = MyUserCreationForm
  97.     list_display = ('username',)
  98.     #list_filter = ('is_admin',)
  99.  
  100.     fieldsets = (
  101.         (None, {'fields': ('username', 'password')}),
  102.         ('Permissions', {'fields': ('is_admin','is_staff','is_active')}),
  103.     )
  104.     add_fieldsets = (
  105.         (None, {
  106.             'classes': ('wide',),
  107.             'fields': ('company', 'username', 'password1', 'password2')}
  108.         ),
  109.     )
  110.     search_fields = ('username',)
  111.     ordering = ('username',)
  112.     filter_horizontal = ()
  113.  
  114. admin.site.register(Company)
  115. admin.site.register(MyGroup)
  116. admin.site.register(MyUser, MyUserAdmin)
Advertisement
Add Comment
Please, Sign In to add comment