Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Make use of new ability to override admin add form templates and remo…

…ved a litle bit of redundancy in the templates.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@12218 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit c4470e5ced090075adbef36b98b051c5a53f7a2e 1 parent a205691
Jannis Leidel authored January 12, 2010
32  django/contrib/admin/templates/admin/auth/user/add_form.html
... ...
@@ -1,33 +1,11 @@
1 1
 {% extends "admin/change_form.html" %}
2 2
 {% load i18n %}
3 3
 
4  
-{% block after_field_sets %}
5  
-
6  
-<p>{% trans "First, enter a username and password. Then, you'll be able to edit more user options." %}</p>
7  
-
8  
-<fieldset class="module aligned">
9  
-
10  
-<div class="form-row">
11  
-  {{ form.username.errors }}
12  
-  {# TODO: get required class on label_tag #}
13  
-  <label for="id_username" class="required">{% trans 'Username' %}:</label> {{ form.username }}
14  
-  <p class="help">{{ form.username.help_text }}</p>
15  
-</div>
16  
-
17  
-<div class="form-row">
18  
-  {{ form.password1.errors }}
19  
-  {# TODO: get required class on label_tag #}
20  
-  <label for="id_password1" class="required">{% trans 'Password' %}:</label> {{ form.password1 }}
21  
-</div>
22  
-
23  
-<div class="form-row">
24  
-  {{ form.password2.errors }}
25  
-  {# TODO: get required class on label_tag #}
26  
-  <label for="id_password2" class="required">{% trans 'Password (again)' %}:</label> {{ form.password2 }}
27  
-  <p class="help">{% trans 'Enter the same password as above, for verification.' %}</p>
28  
-</div>
  4
+{% block form_top %}
  5
+    <p>{% trans "First, enter a username and password. Then, you'll be able to edit more user options." %}</p>
  6
+    <input type="hidden" name="_continue" value="1" />
  7
+{% endblock %}
29 8
 
  9
+{% block after_field_sets %}
30 10
 <script type="text/javascript">document.getElementById("id_username").focus();</script>
31  
-
32  
-</fieldset>
33 11
 {% endblock %}
44  django/contrib/admin/templates/registration/password_change_form.html
... ...
@@ -1,26 +1,50 @@
1 1
 {% extends "admin/base_site.html" %}
2  
-{% load i18n %}
  2
+{% load i18n adminmedia %}
  3
+{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% admin_media_prefix %}css/forms.css" />{% endblock %}
3 4
 {% block userlinks %}{% url django-admindocs-docroot as docsroot %}{% if docsroot %}<a href="{{ docsroot }}">{% trans 'Documentation' %}</a> / {% endif %} {% trans 'Change password' %} / <a href="../logout/">{% trans 'Log out' %}</a>{% endblock %}
4 5
 {% block breadcrumbs %}<div class="breadcrumbs"><a href="../">{% trans 'Home' %}</a> &rsaquo; {% trans 'Password change' %}</div>{% endblock %}
5 6
 
6 7
 {% block title %}{% trans 'Password change' %}{% endblock %}
7 8
 
8  
-{% block content %}
  9
+{% block content %}<div id="content-main">
  10
+
  11
+<form action="" method="post">{% csrf_token %}
  12
+<div>
  13
+{% if form.errors %}
  14
+    <p class="errornote">
  15
+    {% blocktrans count form.errors.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
  16
+    </p>
  17
+{% endif %}
9 18
 
10 19
 <h1>{% trans 'Password change' %}</h1>
11 20
 
12 21
 <p>{% trans "Please enter your old password, for security's sake, and then enter your new password twice so we can verify you typed it in correctly." %}</p>
13 22
 
14  
-<form action="" method="post">{% csrf_token %}
  23
+<fieldset class="module aligned wide">
  24
+
  25
+<div class="form-row">
  26
+    {{ form.old_password.errors }}
  27
+    <label for="id_old_password" class="required">{% trans 'Old password' %}:</label>{{ form.old_password }}
  28
+</div>
15 29
 
16  
-{{ form.old_password.errors }}
17  
-<p class="aligned wide"><label for="id_old_password">{% trans 'Old password:' %}</label>{{ form.old_password }}</p>
18  
-{{ form.new_password1.errors }}
19  
-<p class="aligned wide"><label for="id_new_password1">{% trans 'New password:' %}</label>{{ form.new_password1 }}</p>
  30
+<div class="form-row">
  31
+    {{ form.new_password1.errors }}
  32
+    <label for="id_new_password1" class="required">{% trans 'New password' %}:</label>{{ form.new_password1 }}
  33
+</div>
  34
+
  35
+<div class="form-row">
20 36
 {{ form.new_password2.errors }}
21  
-<p class="aligned wide"><label for="id_new_password2">{% trans 'Confirm password:' %}</label>{{ form.new_password2 }}</p>
  37
+    <label for="id_new_password2" class="required">{% trans 'Password (again)' %}:</label>{{ form.new_password2 }}
  38
+</div>
  39
+
  40
+</fieldset>
  41
+
  42
+<div class="submit-row">
  43
+    <input type="submit" value="{% trans 'Change my password' %}" class="default" />
  44
+</div>
22 45
 
23  
-<p><input type="submit" value="{% trans 'Change my password' %}" /></p>
24  
-</form>
  46
+<script type="text/javascript">document.getElementById("id_old_password").focus();</script>
  47
+</div>
  48
+</form></div>
25 49
 
26 50
 {% endblock %}
81  django/contrib/auth/admin.py
... ...
@@ -1,4 +1,5 @@
1 1
 from django import template
  2
+from django.db import transaction
2 3
 from django.conf import settings
3 4
 from django.contrib import admin
4 5
 from django.contrib.auth.forms import UserCreationForm, UserChangeForm, AdminPasswordChangeForm
@@ -10,6 +11,7 @@
10 11
 from django.template import RequestContext
11 12
 from django.utils.html import escape
12 13
 from django.utils.translation import ugettext, ugettext_lazy as _
  14
+from django.views.decorators.csrf import csrf_protect
13 15
 
14 16
 class GroupAdmin(admin.ModelAdmin):
15 17
     search_fields = ('name',)
@@ -17,6 +19,8 @@ class GroupAdmin(admin.ModelAdmin):
17 19
     filter_horizontal = ('permissions',)
18 20
 
19 21
 class UserAdmin(admin.ModelAdmin):
  22
+    add_form_template = 'admin/auth/user/add_form.html'
  23
+    change_user_password_template = None
20 24
     fieldsets = (
21 25
         (None, {'fields': ('username', 'password')}),
22 26
         (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
@@ -24,6 +28,12 @@ class UserAdmin(admin.ModelAdmin):
24 28
         (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
25 29
         (_('Groups'), {'fields': ('groups',)}),
26 30
     )
  31
+    add_fieldsets = (
  32
+        (None, {
  33
+            'classes': ('wide',),
  34
+            'fields': ('username', 'password1', 'password2')}
  35
+        ),
  36
+    )
27 37
     form = UserChangeForm
28 38
     add_form = UserCreationForm
29 39
     change_password_form = AdminPasswordChangeForm
@@ -41,14 +51,34 @@ def __call__(self, request, url):
41 51
         if url.endswith('password'):
42 52
             return self.user_change_password(request, url.split('/')[0])
43 53
         return super(UserAdmin, self).__call__(request, url)
44  
-    
  54
+
  55
+    def get_fieldsets(self, request, obj=None):
  56
+        if not obj:
  57
+            return self.add_fieldsets
  58
+        return super(UserAdmin, self).get_fieldsets(request, obj)
  59
+
  60
+    def get_form(self, request, obj=None, **kwargs):
  61
+        """
  62
+        Use special form during user creation
  63
+        """
  64
+        defaults = {}
  65
+        if not obj:
  66
+            defaults = {
  67
+                'form': UserCreationForm,
  68
+                'fields': ['username'],
  69
+            }
  70
+        defaults.update(kwargs)
  71
+        return super(UserAdmin, self).get_form(request, obj, **defaults)
  72
+
45 73
     def get_urls(self):
46 74
         from django.conf.urls.defaults import patterns
47 75
         return patterns('',
48 76
             (r'^(\d+)/password/$', self.admin_site.admin_view(self.user_change_password))
49 77
         ) + super(UserAdmin, self).get_urls()
50 78
 
51  
-    def add_view(self, request):
  79
+    @csrf_protect
  80
+    @transaction.commit_on_success
  81
+    def add_view(self, request, form_url='', extra_context=None):
52 82
         # It's an error for a user to have add permission but NOT change
53 83
         # permission for users. If we allowed such users to add users, they
54 84
         # could create superusers, which would mean they would essentially have
@@ -61,41 +91,14 @@ def add_view(self, request):
61 91
                 # error message.
62 92
                 raise Http404('Your user does not have the "Change user" permission. In order to add users, Django requires that your user account have both the "Add user" and "Change user" permissions set.')
63 93
             raise PermissionDenied
64  
-        if request.method == 'POST':
65  
-            form = self.add_form(request.POST)
66  
-            if form.is_valid():
67  
-                new_user = form.save()
68  
-                msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_user}
69  
-                self.log_addition(request, new_user)
70  
-                if "_addanother" in request.POST:
71  
-                    messages.success(request, msg)
72  
-                    return HttpResponseRedirect(request.path)
73  
-                elif '_popup' in request.REQUEST:
74  
-                    return self.response_add(request, new_user)
75  
-                else:
76  
-                    messages.success(request, msg + ' ' +
77  
-                                     ugettext("You may edit it again below."))
78  
-                    return HttpResponseRedirect('../%s/' % new_user.id)
79  
-        else:
80  
-            form = self.add_form()
81  
-        return render_to_response('admin/auth/user/add_form.html', {
82  
-            'title': _('Add user'),
83  
-            'form': form,
84  
-            'is_popup': '_popup' in request.REQUEST,
85  
-            'add': True,
86  
-            'change': False,
87  
-            'has_add_permission': True,
88  
-            'has_delete_permission': False,
89  
-            'has_change_permission': True,
90  
-            'has_file_field': False,
91  
-            'has_absolute_url': False,
  94
+        if extra_context is None:
  95
+            extra_context = {}
  96
+        defaults = {
92 97
             'auto_populated_fields': (),
93  
-            'opts': self.model._meta,
94  
-            'save_as': False,
95 98
             'username_help_text': self.model._meta.get_field('username').help_text,
96  
-            'root_path': self.admin_site.root_path,
97  
-            'app_label': self.model._meta.app_label,            
98  
-        }, context_instance=template.RequestContext(request))
  99
+        }
  100
+        extra_context.update(defaults)
  101
+        return super(UserAdmin, self).add_view(request, form_url, extra_context)
99 102
 
100 103
     def user_change_password(self, request, id):
101 104
         if not self.has_change_permission(request):
@@ -110,8 +113,14 @@ def user_change_password(self, request, id):
110 113
                 return HttpResponseRedirect('..')
111 114
         else:
112 115
             form = self.change_password_form(user)
113  
-        return render_to_response('admin/auth/user/change_password.html', {
  116
+
  117
+        fieldsets = [(None, {'fields': form.base_fields.keys()})]
  118
+        adminForm = admin.helpers.AdminForm(form, fieldsets, {})
  119
+        print adminForm, form
  120
+
  121
+        return render_to_response(self.change_user_password_template or 'admin/auth/user/change_password.html', {
114 122
             'title': _('Change password: %s') % escape(user.username),
  123
+            'adminForm': adminForm,
115 124
             'form': form,
116 125
             'is_popup': '_popup' in request.REQUEST,
117 126
             'add': True,
3  django/contrib/auth/forms.py
@@ -15,7 +15,8 @@ class UserCreationForm(forms.ModelForm):
15 15
         help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."),
16 16
         error_message = _("This value must contain only letters, numbers and underscores."))
17 17
     password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
18  
-    password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput)
  18
+    password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput,
  19
+        help_text = _("Enter the same password as above, for verification."))
19 20
 
20 21
     class Meta:
21 22
         model = User
39  tests/regressiontests/admin_views/tests.py
@@ -1795,27 +1795,30 @@ class IncompleteFormTest(TestCase):
1795 1795
     fixtures = ['admin-views-users.xml']
1796 1796
 
1797 1797
     def setUp(self):
1798  
-       self.client.login(username='super', password='secret')
  1798
+        self.client.login(username='super', password='secret')
1799 1799
 
1800 1800
     def tearDown(self):
1801  
-       self.client.logout()
  1801
+        self.client.logout()
1802 1802
 
1803 1803
     def test_user_creation(self):
1804  
-       response = self.client.post('/test_admin/admin/auth/user/add/', {
1805  
-           'username': 'newuser',
1806  
-           'password1': 'newpassword',
1807  
-           'password2': 'newpassword',
1808  
-       })
1809  
-       new_user = User.objects.order_by('-id')[0]
1810  
-       self.assertRedirects(response, '/test_admin/admin/auth/user/%s/' % new_user.pk)
1811  
-       self.assertNotEquals(new_user.password, UNUSABLE_PASSWORD)
  1804
+        response = self.client.post('/test_admin/admin/auth/user/add/', {
  1805
+            'username': 'newuser',
  1806
+            'password1': 'newpassword',
  1807
+            'password2': 'newpassword',
  1808
+            '_continue': '1',
  1809
+        })
  1810
+        new_user = User.objects.order_by('-id')[0]
  1811
+        self.assertRedirects(response, '/test_admin/admin/auth/user/%s/' % new_user.pk)
  1812
+        self.assertNotEquals(new_user.password, UNUSABLE_PASSWORD)
1812 1813
 
1813 1814
     def test_password_mismatch(self):
1814  
-       response = self.client.post('/test_admin/admin/auth/user/add/', {
1815  
-           'username': 'newuser',
1816  
-           'password1': 'newpassword',
1817  
-           'password2': 'mismatch',
1818  
-       })
1819  
-       self.assertEquals(response.status_code, 200)
1820  
-       self.assert_('password' not in response.context['form'].errors)
1821  
-       self.assertFormError(response, 'form', 'password2', ["The two password fields didn't match."])
  1815
+        response = self.client.post('/test_admin/admin/auth/user/add/', {
  1816
+            'username': 'newuser',
  1817
+            'password1': 'newpassword',
  1818
+            'password2': 'mismatch',
  1819
+        })
  1820
+        self.assertEquals(response.status_code, 200)
  1821
+        adminform = response.context['adminform']
  1822
+        self.assert_('password' not in adminform.form.errors)
  1823
+        self.assertEquals(adminform.form.errors['password2'],
  1824
+                          [u"The two password fields didn't match."])

0 notes on commit c4470e5

Please sign in to comment.
Something went wrong with that request. Please try again.