Hello site
[auf_framonde.git] / eggs / Django-1.4.5-py2.7.egg / django / contrib / auth / admin.py
1 from django.db import transaction
2 from django.conf import settings
3 from django.contrib import admin
4 from django.contrib.auth.forms import (UserCreationForm, UserChangeForm,
5 AdminPasswordChangeForm)
6 from django.contrib.auth.models import User, Group
7 from django.contrib import messages
8 from django.core.exceptions import PermissionDenied
9 from django.http import HttpResponseRedirect, Http404
10 from django.shortcuts import get_object_or_404
11 from django.template.response import TemplateResponse
12 from django.utils.html import escape
13 from django.utils.decorators import method_decorator
14 from django.utils.safestring import mark_safe
15 from django.utils.translation import ugettext, ugettext_lazy as _
16 from django.views.decorators.csrf import csrf_protect
17 from django.views.decorators.debug import sensitive_post_parameters
18
19 csrf_protect_m = method_decorator(csrf_protect)
20
21 class GroupAdmin(admin.ModelAdmin):
22 search_fields = ('name',)
23 ordering = ('name',)
24 filter_horizontal = ('permissions',)
25
26 def formfield_for_manytomany(self, db_field, request=None, **kwargs):
27 if db_field.name == 'permissions':
28 qs = kwargs.get('queryset', db_field.rel.to.objects)
29 # Avoid a major performance hit resolving permission names which
30 # triggers a content_type load:
31 kwargs['queryset'] = qs.select_related('content_type')
32 return super(GroupAdmin, self).formfield_for_manytomany(
33 db_field, request=request, **kwargs)
34
35
36 class UserAdmin(admin.ModelAdmin):
37 add_form_template = 'admin/auth/user/add_form.html'
38 change_user_password_template = None
39 fieldsets = (
40 (None, {'fields': ('username', 'password')}),
41 (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
42 (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
43 'groups', 'user_permissions')}),
44 (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
45 )
46 add_fieldsets = (
47 (None, {
48 'classes': ('wide',),
49 'fields': ('username', 'password1', 'password2')}
50 ),
51 )
52 form = UserChangeForm
53 add_form = UserCreationForm
54 change_password_form = AdminPasswordChangeForm
55 list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
56 list_filter = ('is_staff', 'is_superuser', 'is_active')
57 search_fields = ('username', 'first_name', 'last_name', 'email')
58 ordering = ('username',)
59 filter_horizontal = ('user_permissions',)
60
61 def get_fieldsets(self, request, obj=None):
62 if not obj:
63 return self.add_fieldsets
64 return super(UserAdmin, self).get_fieldsets(request, obj)
65
66 def get_form(self, request, obj=None, **kwargs):
67 """
68 Use special form during user creation
69 """
70 defaults = {}
71 if obj is None:
72 defaults.update({
73 'form': self.add_form,
74 'fields': admin.util.flatten_fieldsets(self.add_fieldsets),
75 })
76 defaults.update(kwargs)
77 return super(UserAdmin, self).get_form(request, obj, **defaults)
78
79 def get_urls(self):
80 from django.conf.urls import patterns
81 return patterns('',
82 (r'^(\d+)/password/$',
83 self.admin_site.admin_view(self.user_change_password))
84 ) + super(UserAdmin, self).get_urls()
85
86 @sensitive_post_parameters()
87 @csrf_protect_m
88 @transaction.commit_on_success
89 def add_view(self, request, form_url='', extra_context=None):
90 # It's an error for a user to have add permission but NOT change
91 # permission for users. If we allowed such users to add users, they
92 # could create superusers, which would mean they would essentially have
93 # the permission to change users. To avoid the problem entirely, we
94 # disallow users from adding users if they don't have change
95 # permission.
96 if not self.has_change_permission(request):
97 if self.has_add_permission(request) and settings.DEBUG:
98 # Raise Http404 in debug mode so that the user gets a helpful
99 # error message.
100 raise Http404(
101 'Your user does not have the "Change user" permission. In '
102 'order to add users, Django requires that your user '
103 'account have both the "Add user" and "Change user" '
104 'permissions set.')
105 raise PermissionDenied
106 if extra_context is None:
107 extra_context = {}
108 defaults = {
109 'auto_populated_fields': (),
110 'username_help_text': self.model._meta.get_field('username').help_text,
111 }
112 extra_context.update(defaults)
113 return super(UserAdmin, self).add_view(request, form_url,
114 extra_context)
115
116 @sensitive_post_parameters()
117 def user_change_password(self, request, id, form_url=''):
118 if not self.has_change_permission(request):
119 raise PermissionDenied
120 user = get_object_or_404(self.queryset(request), pk=id)
121 if request.method == 'POST':
122 form = self.change_password_form(user, request.POST)
123 if form.is_valid():
124 form.save()
125 msg = ugettext('Password changed successfully.')
126 messages.success(request, msg)
127 return HttpResponseRedirect('..')
128 else:
129 form = self.change_password_form(user)
130
131 fieldsets = [(None, {'fields': form.base_fields.keys()})]
132 adminForm = admin.helpers.AdminForm(form, fieldsets, {})
133
134 context = {
135 'title': _('Change password: %s') % escape(user.username),
136 'adminForm': adminForm,
137 'form_url': mark_safe(form_url),
138 'form': form,
139 'is_popup': '_popup' in request.REQUEST,
140 'add': True,
141 'change': False,
142 'has_delete_permission': False,
143 'has_change_permission': True,
144 'has_absolute_url': False,
145 'opts': self.model._meta,
146 'original': user,
147 'save_as': False,
148 'show_save': True,
149 }
150 return TemplateResponse(request, [
151 self.change_user_password_template or
152 'admin/auth/user/change_password.html'
153 ], context, current_app=self.admin_site.name)
154
155 def response_add(self, request, obj, post_url_continue='../%s/'):
156 """
157 Determines the HttpResponse for the add_view stage. It mostly defers to
158 its superclass implementation but is customized because the User model
159 has a slightly different workflow.
160 """
161 # We should allow further modification of the user just added i.e. the
162 # 'Save' button should behave like the 'Save and continue editing'
163 # button except in two scenarios:
164 # * The user has pressed the 'Save and add another' button
165 # * We are adding a user in a popup
166 if '_addanother' not in request.POST and '_popup' not in request.POST:
167 request.POST['_continue'] = 1
168 return super(UserAdmin, self).response_add(request, obj,
169 post_url_continue)
170
171 admin.site.register(Group, GroupAdmin)
172 admin.site.register(User, UserAdmin)
173