You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

206 lines
8.5 KiB

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