Ticket #6083: 6083_nfa_newforms_auth.diff

File 6083_nfa_newforms_auth.diff, 21.7 KB (added by Brian Rosner, 16 years ago)

patch against newforms-admin.

  • django/contrib/admin/templates/admin/auth/user/add_form.html

    diff --git a/django/contrib/admin/templates/admin/auth/user/add_form.html b/django/contrib/admin/templates/admin/auth/user/add_form.html
    index d478ec7..65824a6 100644
    a b  
    88<fieldset class="module aligned">
    99
    1010<div class="form-row">
    11   {{ form.username.html_error_list }}
     11  {{ form.username.errors }}
     12  {# TODO: get required class on label_tag #}
    1213  <label for="id_username" class="required">{% trans 'Username' %}:</label> {{ form.username }}
    13   <p class="help">{{ username_help_text }}</p>
     14  <p class="help">{{ form.username.help_text }}</p>
    1415</div>
    1516
    1617<div class="form-row">
    17   {{ form.password1.html_error_list }}
     18  {{ form.password1.errors }}
     19  {# TODO: get required class on label_tag #}
    1820  <label for="id_password1" class="required">{% trans 'Password' %}:</label> {{ form.password1 }}
    1921</div>
    2022
    2123<div class="form-row">
    22   {{ form.password2.html_error_list }}
     24  {{ form.password2.errors }}
     25  {# TODO: get required class on label_tag #}
    2326  <label for="id_password2" class="required">{% trans 'Password (again)' %}:</label> {{ form.password2 }}
    2427  <p class="help">{% trans 'Enter the same password as above, for verification.' %}</p>
    2528</div>
  • django/contrib/admin/templates/admin/auth/user/change_password.html

    diff --git a/django/contrib/admin/templates/admin/auth/user/change_password.html b/django/contrib/admin/templates/admin/auth/user/change_password.html
    index a75ad87..5740feb 100644
    a b  
    1818<form action="{{ form_url }}" method="post" id="{{ opts.module_name }}_form">{% block form_top %}{% endblock %}
    1919<div>
    2020{% if is_popup %}<input type="hidden" name="_popup" value="1" />{% endif %}
    21 {% if form.error_dict %}
     21{% if form.errors %}
    2222    <p class="errornote">
    23     {% blocktrans count form.error_dict.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
     23    {% blocktrans count form.errors.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
    2424    </p>
    2525{% endif %}
    2626
     
    2929<fieldset class="module aligned">
    3030
    3131<div class="form-row">
    32   {{ form.password1.html_error_list }}
     32  {{ form.password1.errors }}
     33  {# TODO: get required class on label_tag #}
    3334  <label for="id_password1" class="required">{% trans 'Password' %}:</label> {{ form.password1 }}
    3435</div>
    3536
    3637<div class="form-row">
    37   {{ form.password2.html_error_list }}
     38  {{ form.password2.errors }}
     39  {# TODO: get required class on label_tag #}
    3840  <label for="id_password2" class="required">{% trans 'Password (again)' %}:</label> {{ form.password2 }}
    3941  <p class="help">{% trans 'Enter the same password as above, for verification.' %}</p>
    4042</div>
  • django/contrib/auth/admin.py

    diff --git a/django/contrib/auth/admin.py b/django/contrib/auth/admin.py
    index 97d284c..3900e05 100644
    a b class UserAdmin(admin.ModelAdmin):  
    2727    def add_view(self, request):
    2828        if not self.has_change_permission(request):
    2929            raise PermissionDenied
    30         manipulator = UserCreationForm()
    3130        if request.method == 'POST':
    32             new_data = request.POST.copy()
    33             errors = manipulator.get_validation_errors(new_data)
    34             if not errors:
    35                 new_user = manipulator.save(new_data)
     31            form = UserCreationForm(request.POST)
     32            if form.is_valid():
     33                new_user = form.save()
    3634                msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_user}
    3735                if "_addanother" in request.POST:
    3836                    request.user.message_set.create(message=msg)
    class UserAdmin(admin.ModelAdmin):  
    4139                    request.user.message_set.create(message=msg + ' ' + ugettext("You may edit it again below."))
    4240                    return HttpResponseRedirect('../%s/' % new_user.id)
    4341        else:
    44             errors = new_data = {}
    45         form = oldforms.FormWrapper(manipulator, new_data, errors)
     42            form = UserCreationForm()
    4643        return render_to_response('admin/auth/user/add_form.html', {
    4744            'title': _('Add user'),
    4845            'form': form,
  • django/contrib/auth/forms.py

    diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py
    index 47a974c..9905951 100644
    a b from django.contrib.sites.models import Site  
    44from django.template import Context, loader
    55from django.core import validators
    66from django import oldforms
     7from django import newforms as forms
    78from django.utils.translation import ugettext as _
    89
    9 class UserCreationForm(oldforms.Manipulator):
    10     "A form that creates a user, with no privileges, from the given username and password."
    11     def __init__(self):
    12         self.fields = (
    13             oldforms.TextField(field_name='username', length=30, max_length=30, is_required=True,
    14                 validator_list=[validators.isAlphaNumeric, self.isValidUsername]),
    15             oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True),
    16             oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True,
    17                 validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
    18         )
    19 
    20     def isValidUsername(self, field_data, all_data):
     10class UserCreationForm(forms.ModelForm):
     11    """
     12    A form that creates a user, with no privileges, from the given username and password.
     13    """
     14    username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^\w+$',
     15        help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."),
     16        error_message = _("This value must contain only letters, numbers and underscores."))
     17    password1 = forms.CharField(label=_("Password"), max_length=60, widget=forms.PasswordInput)
     18    password2 = forms.CharField(label=_("Password confirmation"), max_length=60, widget=forms.PasswordInput)
     19   
     20    class Meta:
     21        model = User
     22        fields = ("username",)
     23   
     24    def clean_username(self):
     25        username = self.cleaned_data["username"]
    2126        try:
    22             User.objects.get(username=field_data)
     27            User.objects.get(username=username)
    2328        except User.DoesNotExist:
    24             return
    25         raise validators.ValidationError, _('A user with that username already exists.')
    26 
    27     def save(self, new_data):
    28         "Creates the user."
    29         return User.objects.create_user(new_data['username'], '', new_data['password1'])
     29            return username
     30        raise forms.ValidationError(_("A user with that username already exists."))
     31   
     32    def clean_password2(self):
     33        password1 = self.cleaned_data["password1"]
     34        password2 = self.cleaned_data["password2"]
     35        if password1 != password2:
     36            raise forms.ValidationError(_("The two password fields didn't match."))
     37        return password2
     38   
     39    def save(self, commit=True):
     40        user = super(UserCreationForm, self).save(commit=False)
     41        user.set_password(self.cleaned_data["password1"])
     42        if commit:
     43            user.save()
     44        return user
    3045
    31 class AuthenticationForm(oldforms.Manipulator):
     46class AuthenticationForm(forms.Form):
    3247    """
    3348    Base class for authenticating users. Extend this to get a form that accepts
    3449    username/password logins.
    3550    """
    36     def __init__(self, request=None):
     51    username = forms.CharField(max_length=30)
     52    password = forms.CharField(max_length=30, widget=forms.PasswordInput)
     53   
     54    def __init__(self, request=None, *args, **kwargs):
    3755        """
    38         If request is passed in, the manipulator will validate that cookies are
     56        If request is passed in, the form will validate that cookies are
    3957        enabled. Note that the request (a HttpRequest object) must have set a
    4058        cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
    41         running this validator.
     59        running this validation.
    4260        """
    4361        self.request = request
    44         self.fields = [
    45             oldforms.TextField(field_name="username", length=15, max_length=30, is_required=True,
    46                 validator_list=[self.isValidUser, self.hasCookiesEnabled]),
    47             oldforms.PasswordField(field_name="password", length=15, max_length=30, is_required=True),
    48         ]
    4962        self.user_cache = None
    50 
    51     def hasCookiesEnabled(self, field_data, all_data):
    52         if self.request and not self.request.session.test_cookie_worked():
    53             raise validators.ValidationError, _("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in.")
    54 
    55     def isValidUser(self, field_data, all_data):
    56         username = field_data
    57         password = all_data.get('password', None)
     63        super(AuthenticationForm, self).__init__(*args, **kwargs)
     64   
     65    def clean(self):
     66        username = self.cleaned_data.get('username')
     67        password = self.cleaned_data.get('password')
     68       
    5869        self.user_cache = authenticate(username=username, password=password)
    5970        if self.user_cache is None:
    60             raise validators.ValidationError, _("Please enter a correct username and password. Note that both fields are case-sensitive.")
    61         elif not self.user_cache.is_active:
    62             raise validators.ValidationError, _("This account is inactive.")
    63 
     71            raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
     72        elif self.user_cache.is_active:
     73            raise forms.ValidationError(_("This account is inactive."))
     74       
     75        # TODO: determine whether this should move to its own method.
     76        if self.request:
     77            if not self.request.session.test_cookie_worked():
     78                raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))
     79       
     80        return self.cleaned_data
     81   
    6482    def get_user_id(self):
    6583        if self.user_cache:
    6684            return self.user_cache.id
    6785        return None
    68 
     86   
    6987    def get_user(self):
    7088        return self.user_cache
    7189
    72 class PasswordResetForm(oldforms.Manipulator):
    73     "A form that lets a user request a password reset"
    74     def __init__(self):
    75         self.fields = (
    76             oldforms.EmailField(field_name="email", length=40, is_required=True,
    77                 validator_list=[self.isValidUserEmail]),
    78         )
    79 
    80     def isValidUserEmail(self, new_data, all_data):
    81         "Validates that a user exists with the given e-mail address"
    82         self.users_cache = list(User.objects.filter(email__iexact=new_data))
     90class PasswordResetForm(forms.Form):
     91    # used to be length of 40
     92    email = forms.EmailField()
     93   
     94    def clean_email(self):
     95        """
     96        Validates that a user exists with the given e-mail address.
     97        """
     98        email = self.cleaned_data["email"]
     99        self.users_cache = User.objects.filter(email__iexact=email)
    83100        if len(self.users_cache) == 0:
    84             raise validators.ValidationError, _("That e-mail address doesn't have an associated user account. Are you sure you've registered?")
    85 
     101            raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?"))
     102   
    86103    def save(self, domain_override=None, email_template_name='registration/password_reset_email.html'):
    87         "Calculates a new password randomly and sends it to the user"
     104        """
     105        Calculates a new password randomly and sends it to the user.
     106        """
    88107        from django.core.mail import send_mail
    89108        for user in self.users_cache:
    90109            new_pass = User.objects.make_random_password()
    class PasswordResetForm(oldforms.Manipulator):  
    103122                'domain': domain,
    104123                'site_name': site_name,
    105124                'user': user,
    106                 }
    107             send_mail(_('Password reset on %s') % site_name, t.render(Context(c)), None, [user.email])
     125            }
     126            send_mail(_("Password reset on %s") % site_name,
     127                t.render(Context(c)), None, [user.email])
    108128
    109 class PasswordChangeForm(oldforms.Manipulator):
    110     "A form that lets a user change his password."
    111     def __init__(self, user):
     129class PasswordChangeForm(forms.Form):
     130    """
     131    A form that lets a user change his/her password.
     132    """
     133    old_password = forms.CharField(max_length=30, widget=forms.PasswordInput)
     134    new_password1 = forms.CharField(max_length=30, widget=forms.PasswordInput)
     135    new_password2 = forms.CharField(max_length=30, widget=forms.PasswordInput)
     136   
     137    def __init__(self, user, *args, **kwargs):
    112138        self.user = user
    113         self.fields = (
    114             oldforms.PasswordField(field_name="old_password", length=30, max_length=30, is_required=True,
    115                 validator_list=[self.isValidOldPassword]),
    116             oldforms.PasswordField(field_name="new_password1", length=30, max_length=30, is_required=True,
    117                 validator_list=[validators.AlwaysMatchesOtherField('new_password2', _("The two 'new password' fields didn't match."))]),
    118             oldforms.PasswordField(field_name="new_password2", length=30, max_length=30, is_required=True),
    119         )
    120 
    121     def isValidOldPassword(self, new_data, all_data):
    122         "Validates that the old_password field is correct."
    123         if not self.user.check_password(new_data):
    124             raise validators.ValidationError, _("Your old password was entered incorrectly. Please enter it again.")
    125 
    126     def save(self, new_data):
    127         "Saves the new password."
    128         self.user.set_password(new_data['new_password1'])
    129         self.user.save()
    130 
    131 class AdminPasswordChangeForm(oldforms.Manipulator):
    132     "A form used to change the password of a user in the admin interface."
    133     def __init__(self, user):
     139        super(PasswordChangeForm, self).__init__(*args, **kwargs)
     140   
     141    def clean_old_password(self):
     142        """
     143        Validates that the old_password field is correct.
     144        """
     145        old_password = self.cleaned_data["old_password"]
     146        if not self.user.check_password(old_password):
     147            raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again."))
     148        return old_password
     149   
     150    def save(self, commit=True):
     151        self.user.set_password(self.cleaned_data['new_password1'])
     152        if commit:
     153            self.user.save()
     154        return self.user
     155
     156class AdminPasswordChangeForm(forms.Form):
     157    """
     158    A form used to change the password of a user in the admin interface.
     159    """
     160    password1 = forms.CharField(max_length=60, widget=forms.PasswordInput)
     161    password2 = forms.CharField(max_length=60, widget=forms.PasswordInput)
     162   
     163    def __init__(self, user, *args, **kwargs):
    134164        self.user = user
    135         self.fields = (
    136             oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True),
    137             oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True,
    138                 validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
    139         )
    140 
    141     def save(self, new_data):
    142         "Saves the new password."
    143         self.user.set_password(new_data['password1'])
    144         self.user.save()
     165        super(AdminPasswordChangeForm, self).__init__(*args, **kwargs)
     166   
     167    def clean_password2(self):
     168        password1 = self.cleaned_data["password1"]
     169        password2 = self.cleaned_data["password2"]
     170        if password1 != password2:
     171            raise forms.ValidationError(_("The two password fields didn't match."))
     172        return password2
     173   
     174    def save(self, commit=True):
     175        """
     176        Saves the new password.
     177        """
     178        self.user.set_password(self.cleaned_data["password1"])
     179        if commit:
     180            self.user.save()
     181        return self.user
  • django/contrib/auth/views.py

    diff --git a/django/contrib/auth/views.py b/django/contrib/auth/views.py
    index 509b96e..65d6b29 100644
    a b  
    11from django.contrib.auth.forms import AuthenticationForm
    22from django.contrib.auth.forms import PasswordResetForm, PasswordChangeForm, AdminPasswordChangeForm
    33from django.core.exceptions import PermissionDenied
    4 from django import oldforms
    54from django.shortcuts import render_to_response, get_object_or_404
    65from django.template import RequestContext
    76from django.contrib.sites.models import Site, RequestSite
    from django.contrib.auth.models import User  
    1413
    1514def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
    1615    "Displays the login form and handles the login action."
    17     manipulator = AuthenticationForm(request)
    1816    redirect_to = request.REQUEST.get(redirect_field_name, '')
    19     if request.POST:
    20         errors = manipulator.get_validation_errors(request.POST)
    21         if not errors:
     17    if request.method == "POST":
     18        form = AuthenticationForm(request, request.POST)
     19        if form.is_valid():
    2220            # Light security check -- make sure redirect_to isn't garbage.
    2321            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
    2422                from django.conf import settings
    2523                redirect_to = settings.LOGIN_REDIRECT_URL
    2624            from django.contrib.auth import login
    27             login(request, manipulator.get_user())
     25            login(request, form.get_user())
    2826            request.session.delete_test_cookie()
    2927            return HttpResponseRedirect(redirect_to)
    3028    else:
    31         errors = {}
     29        form = AuthenticationForm(request)
    3230    request.session.set_test_cookie()
    33 
    3431    if Site._meta.installed:
    3532        current_site = Site.objects.get_current()
    3633    else:
    3734        current_site = RequestSite(request)
    38 
    3935    return render_to_response(template_name, {
    40         'form': oldforms.FormWrapper(manipulator, request.POST, errors),
     36        'form': form,
    4137        redirect_field_name: redirect_to,
    4238        'site_name': current_site.name,
    4339    }, context_instance=RequestContext(request))
    def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_N  
    6864
    6965def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html',
    7066        email_template_name='registration/password_reset_email.html'):
    71     new_data, errors = {}, {}
    72     form = PasswordResetForm()
    73     if request.POST:
    74         new_data = request.POST.copy()
    75         errors = form.get_validation_errors(new_data)
    76         if not errors:
     67    if request.method == "POST":
     68        form = PasswordResetForm(request.POST)
     69        if form.is_valid():
    7770            if is_admin_site:
    7871                form.save(domain_override=request.META['HTTP_HOST'])
    7972            else:
    8073                form.save(email_template_name=email_template_name)
    8174            return HttpResponseRedirect('%sdone/' % request.path)
    82     return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)},
    83         context_instance=RequestContext(request))
     75    else:
     76        form = PasswordResetForm()
     77    return render_to_response(template_name, {
     78        'form': form,
     79    }, context_instance=RequestContext(request))
    8480
    8581def password_reset_done(request, template_name='registration/password_reset_done.html'):
    8682    return render_to_response(template_name, context_instance=RequestContext(request))
    8783
    8884def password_change(request, template_name='registration/password_change_form.html'):
    89     new_data, errors = {}, {}
    90     form = PasswordChangeForm(request.user)
    91     if request.POST:
    92         new_data = request.POST.copy()
    93         errors = form.get_validation_errors(new_data)
    94         if not errors:
    95             form.save(new_data)
     85    if request.method == "POST":
     86        form = PasswordChangeForm(request.user, request.POST)
     87        if form.is_valid():
     88            form.save()
    9689            return HttpResponseRedirect('%sdone/' % request.path)
    97     return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)},
    98         context_instance=RequestContext(request))
     90    else:
     91        form = PasswordChangeForm(request.user)
     92    return render_to_response(template_name, {
     93        'form': form,
     94    }, context_instance=RequestContext(request))
    9995password_change = login_required(password_change)
    10096
    10197def password_change_done(request, template_name='registration/password_change_done.html'):
    10298    return render_to_response(template_name, context_instance=RequestContext(request))
    10399
     100# TODO: move to admin.py in the ModelAdmin
    104101def user_change_password(request, id):
     102    from django import oldforms
    105103    if not request.user.has_perm('auth.change_user'):
    106104        raise PermissionDenied
    107105    user = get_object_or_404(User, pk=id)
    108     manipulator = AdminPasswordChangeForm(user)
    109106    if request.method == 'POST':
    110         new_data = request.POST.copy()
    111         errors = manipulator.get_validation_errors(new_data)
    112         if not errors:
    113             new_user = manipulator.save(new_data)
     107        form = AdminPasswordChangeForm(user, request.POST)
     108        if form.is_valid():
     109            new_user = form.save()
    114110            msg = _('Password changed successfully.')
    115111            request.user.message_set.create(message=msg)
    116112            return HttpResponseRedirect('..')
    117113    else:
    118         errors = new_data = {}
    119     form = oldforms.FormWrapper(manipulator, new_data, errors)
     114        form = AdminPasswordChangeForm(user)
    120115    return render_to_response('admin/auth/user/change_password.html', {
    121116        'title': _('Change password: %s') % escape(user.username),
    122117        'form': form,
Back to Top