Advertisement
Guest User

Untitled

a guest
May 17th, 2017
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.41 KB | None | 0 0
  1. import json
  2. import warnings
  3.  
  4. from django import forms
  5. from django.contrib.auth import authenticate, get_user_model
  6. from django.template.defaultfilters import capfirst
  7. from django.utils.translation import ugettext_lazy as _
  8. from django.contrib.auth.models import User
  9. from djangular.forms import NgModelFormMixin
  10.  
  11. class RegistrationForm(NgModelFormMixin,forms.Form):
  12.     required_css_class = 'required'
  13.  
  14.     username = forms.RegexField(regex=r'^[\w.@+-]+$',
  15.                                 max_length=30,
  16.                                 label=_("Username"),
  17.                                 error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
  18.     email = forms.EmailField(label=_("E-mail"))
  19.     password1 = forms.CharField(widget=forms.PasswordInput,
  20.                                 label=_("Password"))
  21.     password2 = forms.CharField(widget=forms.PasswordInput,
  22.                                 label=_("Password (again)"))
  23.  
  24.     def __init__(self, *args, **kwargs):
  25.         kwargs.update(scope_prefix='$parent')
  26.         super(RegistrationForm, self).__init__(*args, **kwargs)
  27.  
  28.     def clean_username(self):
  29.         """
  30.        Validate that the username is alphanumeric and is not already
  31.        in use.
  32.  
  33.        """
  34.         existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
  35.         print User.objects.all()
  36.         print existing
  37.         if existing.exists():
  38.             raise forms.ValidationError(_("A user with that username already exists."))
  39.         else:
  40.             return self.cleaned_data['username']
  41.  
  42.     def clean(self):
  43.         """
  44.        Verifiy that the values entered into the two password fields
  45.        match. Note that an error here will end up in
  46.        ``non_field_errors()`` because it doesn't apply to a single
  47.        field.
  48.  
  49.        """
  50.         if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
  51.             if self.cleaned_data['password1'] != self.cleaned_data['password2']:
  52.                 raise forms.ValidationError(_("The two password fields didn't match."))
  53.         return self.cleaned_data
  54.  
  55.  
  56. class AuthenticationForm(NgModelFormMixin, forms.Form):
  57.     username = forms.CharField(max_length=254)
  58.     password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
  59.  
  60.     error_messages = {
  61.         'invalid_login': _("Please enter a correct %(username)s and password. "
  62.                            "Note that both fields may be case-sensitive."),
  63.         'inactive': _("This account is inactive."),
  64.     }
  65.  
  66.     def __init__(self, request=None, *args, **kwargs):
  67.         """
  68.        The 'request' parameter is set for custom auth use by subclasses.
  69.        The form data comes in via the standard 'data' kwarg.
  70.        """
  71.         kwargs.update(scope_prefix='$parent')
  72.         self.request = request
  73.         self.user_cache = None
  74.         super(AuthenticationForm, self).__init__(*args, **kwargs)
  75.  
  76.         # Set the label for the "username" field.
  77.         UserModel = get_user_model()
  78.         self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
  79.         if self.fields['username'].label is None:
  80.             self.fields['username'].label = capfirst(self.username_field.verbose_name)
  81.  
  82.     def clean(self):
  83.         username = self.cleaned_data.get('username')
  84.         password = self.cleaned_data.get('password')
  85.  
  86.         if username and password:
  87.             self.user_cache = authenticate(username=username,
  88.                                            password=password)
  89.             if self.user_cache is None:
  90.                 raise forms.ValidationError(
  91.                     self.error_messages['invalid_login'],
  92.                     code='invalid_login',
  93.                     params={'username': self.username_field.verbose_name},
  94.                 )
  95.             elif not self.user_cache.is_active:
  96.                 raise forms.ValidationError(
  97.                     self.error_messages['inactive'],
  98.                     code='inactive',
  99.                 )
  100.         return self.cleaned_data
  101.  
  102.     def check_for_test_cookie(self):
  103.         warnings.warn("check_for_test_cookie is deprecated; ensure your login "
  104.                       "view is CSRF-protected.", DeprecationWarning)
  105.  
  106.     def get_user_id(self):
  107.         if self.user_cache:
  108.             return self.user_cache.id
  109.         return None
  110.  
  111.     def get_user(self):
  112.         return self.user_cache
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement