Django

Code

Show
Ignore:
Timestamp:
07/19/08 08:30:47 (6 months ago)
Author:
jbronn
Message:

gis: Merged revisions 7921,7926-7928,7938-7941,7945-7947,7949-7950,7952,7955-7956,7961,7964-7968,7970-7978 via svnmerge from trunk.

This includes the newforms-admin branch, and thus is backwards-incompatible. The geographic admin is _not_ in this changeset, and is forthcoming.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/gis

    • Property svnmerge-integrated changed from /django/trunk:1-7917 to /django/trunk:1-7978
  • django/branches/gis/django/contrib/auth/forms.py

    r6672 r7979  
    44from django.template import Context, loader 
    55from django.core import validators 
    6 from django import oldforms 
    7 from django.utils.translation import ugettext as _ 
     6from django import forms 
     7from django.utils.translation import ugettext_lazy as _ 
    88 
    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         ) 
     9class UserCreationForm(forms.ModelForm): 
     10    """ 
     11    A form that creates a user, with no privileges, from the given username and password. 
     12    """ 
     13    username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^\w+$', 
     14        help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."), 
     15        error_message = _("This value must contain only letters, numbers and underscores.")) 
     16    password1 = forms.CharField(label=_("Password"), max_length=60, widget=forms.PasswordInput) 
     17    password2 = forms.CharField(label=_("Password confirmation"), max_length=60, widget=forms.PasswordInput) 
     18     
     19    class Meta: 
     20        model = User 
     21        fields = ("username",) 
     22     
     23    def clean_username(self): 
     24        username = self.cleaned_data["username"] 
     25        try: 
     26            User.objects.get(username=username) 
     27        except User.DoesNotExist: 
     28            return username 
     29        raise forms.ValidationError(_("A user with that username already exists.")) 
     30     
     31    def clean_password2(self): 
     32        password1 = self.cleaned_data["password1"] 
     33        password2 = self.cleaned_data["password2"] 
     34        if password1 != password2: 
     35            raise forms.ValidationError(_("The two password fields didn't match.")) 
     36        return password2 
     37     
     38    def save(self, commit=True): 
     39        user = super(UserCreationForm, self).save(commit=False) 
     40        user.set_password(self.cleaned_data["password1"]) 
     41        if commit: 
     42            user.save() 
     43        return user 
    1944 
    20     def isValidUsername(self, field_data, all_data): 
    21         try: 
    22             User.objects.get(username=field_data) 
    23         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']) 
    30  
    31 class AuthenticationForm(oldforms.Manipulator): 
     45class AuthenticationForm(forms.Form): 
    3246    """ 
    3347    Base class for authenticating users. Extend this to get a form that accepts 
    3448    username/password logins. 
    3549    """ 
    36     def __init__(self, request=None): 
     50    username = forms.CharField(label=_("Username"), max_length=30) 
     51    password = forms.CharField(label=_("Password"), max_length=30, widget=forms.PasswordInput) 
     52     
     53    def __init__(self, request=None, *args, **kwargs): 
    3754        """ 
    38         If request is passed in, the manipulator will validate that cookies are 
     55        If request is passed in, the form will validate that cookies are 
    3956        enabled. Note that the request (a HttpRequest object) must have set a 
    4057        cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before 
    41         running this validator
     58        running this validation
    4259        """ 
    4360        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         ] 
    4961        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) 
    58         self.user_cache = authenticate(username=username, password=password) 
    59         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  
     62        super(AuthenticationForm, self).__init__(*args, **kwargs) 
     63     
     64    def clean(self): 
     65        username = self.cleaned_data.get('username') 
     66        password = self.cleaned_data.get('password') 
     67         
     68        if username and password: 
     69            self.user_cache = authenticate(username=username, password=password) 
     70            if self.user_cache is None: 
     71                raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive.")) 
     72            elif not 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    email = forms.EmailField(label=_("E-mail"), max_length=40) 
     92     
     93    def clean_email(self): 
     94        """ 
     95        Validates that a user exists with the given e-mail address. 
     96        """ 
     97        email = self.cleaned_data["email"] 
     98        self.users_cache = User.objects.filter(email__iexact=email) 
    8399        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  
     100            raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?")
     101     
    86102    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" 
     103        """ 
     104        Calculates a new password randomly and sends it to the user. 
     105        """ 
    88106        from django.core.mail import send_mail 
    89107        for user in self.users_cache: 
     
    104122                'site_name': site_name, 
    105123                'user': user, 
    106                 } 
    107             send_mail(_('Password reset on %s') % site_name, t.render(Context(c)), None, [user.email]) 
     124            } 
     125            send_mail(_("Password reset on %s") % site_name, 
     126                t.render(Context(c)), None, [user.email]) 
    108127 
    109 class PasswordChangeForm(oldforms.Manipulator): 
    110     "A form that lets a user change his password." 
    111     def __init__(self, user): 
     128class PasswordChangeForm(forms.Form): 
     129    """ 
     130    A form that lets a user change his/her password. 
     131    """ 
     132    old_password = forms.CharField(label=_("Old password"), max_length=30, widget=forms.PasswordInput) 
     133    new_password1 = forms.CharField(label=_("New password"), max_length=30, widget=forms.PasswordInput) 
     134    new_password2 = forms.CharField(label=_("New password confirmation"), max_length=30, widget=forms.PasswordInput) 
     135     
     136    def __init__(self, user, *args, **kwargs): 
    112137        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         ) 
     138        super(PasswordChangeForm, self).__init__(*args, **kwargs) 
     139     
     140    def clean_old_password(self): 
     141        """ 
     142        Validates that the old_password field is correct. 
     143        """ 
     144        old_password = self.cleaned_data["old_password"] 
     145        if not self.user.check_password(old_password): 
     146            raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again.")) 
     147        return old_password 
     148     
     149    def clean_new_password2(self): 
     150        password1 = self.cleaned_data.get('new_password1') 
     151        password2 = self.cleaned_data.get('new_password2') 
     152        if password1 and password2: 
     153            if password1 != password2: 
     154                raise forms.ValidationError(_("The two password fields didn't match.")) 
     155        return password2 
     156     
     157    def save(self, commit=True): 
     158        self.user.set_password(self.cleaned_data['new_password1']) 
     159        if commit: 
     160            self.user.save() 
     161        return self.user 
    120162 
    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): 
     163class AdminPasswordChangeForm(forms.Form): 
     164    """ 
     165    A form used to change the password of a user in the admin interface. 
     166    """ 
     167    password1 = forms.CharField(label=_("Password"), max_length=60, widget=forms.PasswordInput) 
     168    password2 = forms.CharField(label=_("Password (again)"), max_length=60, widget=forms.PasswordInput) 
     169     
     170    def __init__(self, user, *args, **kwargs): 
    134171        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() 
     172        super(AdminPasswordChangeForm, self).__init__(*args, **kwargs) 
     173     
     174    def clean_password2(self): 
     175        password1 = self.cleaned_data.get('password1') 
     176        password2 = self.cleaned_data.get('password2') 
     177        if password1 and password2: 
     178            if password1 != password2: 
     179                raise forms.ValidationError(_("The two password fields didn't match.")) 
     180        return password2 
     181     
     182    def save(self, commit=True): 
     183        """ 
     184        Saves the new password. 
     185        """ 
     186        self.user.set_password(self.cleaned_data["password1"]) 
     187        if commit: 
     188            self.user.save() 
     189        return self.user 
  • django/branches/gis/django/contrib/auth/models.py

    r7836 r7979  
    9292    """ 
    9393    name = models.CharField(_('name'), max_length=80, unique=True) 
    94     permissions = models.ManyToManyField(Permission, verbose_name=_('permissions'), blank=True, filter_interface=models.HORIZONTAL
     94    permissions = models.ManyToManyField(Permission, verbose_name=_('permissions'), blank=True
    9595 
    9696    class Meta: 
    9797        verbose_name = _('group') 
    9898        verbose_name_plural = _('groups') 
    99  
    100     class Admin: 
    101         search_fields = ('name',) 
    102         ordering = ('name',) 
    103  
     99         
    104100    def __unicode__(self): 
    105101        return self.name 
     
    148144    groups = models.ManyToManyField(Group, verbose_name=_('groups'), blank=True, 
    149145        help_text=_("In addition to the permissions manually assigned, this user will also get all permissions granted to each group he/she is in.")) 
    150     user_permissions = models.ManyToManyField(Permission, verbose_name=_('user permissions'), blank=True, filter_interface=models.HORIZONTAL
     146    user_permissions = models.ManyToManyField(Permission, verbose_name=_('user permissions'), blank=True
    151147    objects = UserManager() 
    152148 
     
    154150        verbose_name = _('user') 
    155151        verbose_name_plural = _('users') 
    156  
    157     class Admin: 
    158         fields = ( 
    159             (None, {'fields': ('username', 'password')}), 
    160             (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), 
    161             (_('Permissions'), {'fields': ('is_staff', 'is_active', 'is_superuser', 'user_permissions')}), 
    162             (_('Important dates'), {'fields': ('last_login', 'date_joined')}), 
    163             (_('Groups'), {'fields': ('groups',)}), 
    164         ) 
    165         list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff') 
    166         list_filter = ('is_staff', 'is_superuser') 
    167         search_fields = ('username', 'first_name', 'last_name', 'email') 
    168         ordering = ('username',) 
    169  
     152         
    170153    def __unicode__(self): 
    171154        return self.username 
  • django/branches/gis/django/contrib/auth/views.py

    r7768 r7979  
    1 from django import oldforms 
    21from django.contrib.auth import REDIRECT_FIELD_NAME 
    32from django.contrib.auth.decorators import login_required 
    43from django.contrib.auth.forms import AuthenticationForm 
    5 from django.contrib.auth.forms import PasswordResetForm, PasswordChangeForm 
     4from django.contrib.auth.forms import PasswordResetForm, PasswordChangeForm, AdminPasswordChangeForm 
     5from django.core.exceptions import PermissionDenied 
     6from django.shortcuts import render_to_response, get_object_or_404 
    67from django.contrib.sites.models import Site, RequestSite 
    78from django.http import HttpResponseRedirect 
    8 from django.shortcuts import render_to_response 
    99from django.template import RequestContext 
    1010from django.utils.http import urlquote 
     11from django.utils.html import escape 
    1112from django.utils.translation import ugettext as _ 
     13from django.contrib.auth.models import User 
     14import re 
    1215 
    1316def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME): 
    1417    "Displays the login form and handles the login action." 
    15     manipulator = AuthenticationForm() 
    1618    redirect_to = request.REQUEST.get(redirect_field_name, '') 
    17     if request.POST
    18         errors = manipulator.get_validation_errors(request.POST) 
    19         if not errors
     19    if request.method == "POST"
     20        form = AuthenticationForm(data=request.POST) 
     21        if form.is_valid()
    2022            # Light security check -- make sure redirect_to isn't garbage. 
    2123            if not redirect_to or '//' in redirect_to or ' ' in redirect_to: 
     
    2325                redirect_to = settings.LOGIN_REDIRECT_URL 
    2426            from django.contrib.auth import login 
    25             login(request, manipulator.get_user()) 
     27            login(request, form.get_user()) 
    2628            if request.session.test_cookie_worked(): 
    2729                request.session.delete_test_cookie() 
    2830            return HttpResponseRedirect(redirect_to) 
    2931    else: 
    30         errors = {} 
     32        form = AuthenticationForm(request) 
    3133    request.session.set_test_cookie() 
    32  
    3334    if Site._meta.installed: 
    3435        current_site = Site.objects.get_current() 
    3536    else: 
    3637        current_site = RequestSite(request) 
    37  
    3838    return render_to_response(template_name, { 
    39         'form': oldforms.FormWrapper(manipulator, request.POST, errors)
     39        'form': form
    4040        redirect_field_name: redirect_to, 
    4141        'site_name': current_site.name, 
     
    6767 
    6868def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html', 
    69         email_template_name='registration/password_reset_email.html'): 
    70     new_data, errors = {}, {} 
    71     form = PasswordResetForm() 
    72     if request.POST: 
    73         new_data = request.POST.copy() 
    74         errors = form.get_validation_errors(new_data) 
    75         if not errors: 
     69        email_template_name='registration/password_reset_email.html', 
     70        password_reset_form=PasswordResetForm): 
     71    if request.method == "POST": 
     72        form = password_reset_form(request.POST) 
     73        if form.is_valid(): 
    7674            if is_admin_site: 
    7775                form.save(domain_override=request.META['HTTP_HOST']) 
     
    8280                    form.save(domain_override=RequestSite(request).domain, email_template_name=email_template_name) 
    8381            return HttpResponseRedirect('%sdone/' % request.path) 
    84     return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)}, 
    85         context_instance=RequestContext(request)) 
     82    else: 
     83        form = password_reset_form() 
     84    return render_to_response(template_name, { 
     85        'form': form, 
     86    }, context_instance=RequestContext(request)) 
    8687 
    8788def password_reset_done(request, template_name='registration/password_reset_done.html'): 
     
    8990 
    9091def password_change(request, template_name='registration/password_change_form.html'): 
    91     new_data, errors = {}, {} 
    92     form = PasswordChangeForm(request.user) 
    93     if request.POST: 
    94         new_data = request.POST.copy() 
    95         errors = form.get_validation_errors(new_data) 
    96         if not errors: 
    97             form.save(new_data) 
     92    if request.method == "POST": 
     93        form = PasswordChangeForm(request.user, request.POST) 
     94        if form.is_valid(): 
     95            form.save() 
    9896            return HttpResponseRedirect('%sdone/' % request.path) 
    99     return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)}, 
    100         context_instance=RequestContext(request)) 
     97    else: 
     98        form = PasswordChangeForm(request.user) 
     99    return render_to_response(template_name, { 
     100        'form': form, 
     101    }, context_instance=RequestContext(request)) 
    101102password_change = login_required(password_change) 
    102103 
    103104def password_change_done(request, template_name='registration/password_change_done.html'): 
    104105    return render_to_response(template_name, context_instance=RequestContext(request)) 
     106 
     107# TODO: move to admin.py in the ModelAdmin 
     108def user_change_password(request, id): 
     109    if not request.user.has_perm('auth.change_user'): 
     110        raise PermissionDenied 
     111    user = get_object_or_404(User, pk=id) 
     112    if request.method == 'POST': 
     113        form = AdminPasswordChangeForm(user, request.POST) 
     114        if form.is_valid(): 
     115            new_user = form.save() 
     116            msg = _('Password changed successfully.') 
     117            request.user.message_set.create(message=msg) 
     118            return HttpResponseRedirect('..') 
     119    else: 
     120        form = AdminPasswordChangeForm(user) 
     121    return render_to_response('admin/auth/user/change_password.html', { 
     122        'title': _('Change password: %s') % escape(user.username), 
     123        'form': form, 
     124        'is_popup': '_popup' in request.REQUEST, 
     125        'add': True, 
     126        'change': False, 
     127        'has_delete_permission': False, 
     128        'has_change_permission': True, 
     129        'has_absolute_url': False, 
     130        'opts': User._meta, 
     131        'original': user, 
     132        'save_as': False, 
     133        'show_save': True, 
     134        'root_path': re.sub('auth/user/(\d+)/password/$', '', request.path), 
     135    }, context_instance=RequestContext(request))