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.

admin.py 8.4KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. from django.conf import settings
  2. from django.contrib import admin, messages
  3. from django.contrib.admin.options import IS_POPUP_VAR
  4. from django.contrib.admin.utils import unquote
  5. from django.contrib.auth import update_session_auth_hash
  6. from django.contrib.auth.forms import (
  7. AdminPasswordChangeForm, UserChangeForm, UserCreationForm,
  8. )
  9. from django.contrib.auth.models import Group, User
  10. from django.core.exceptions import PermissionDenied
  11. from django.db import router, transaction
  12. from django.http import Http404, HttpResponseRedirect
  13. from django.template.response import TemplateResponse
  14. from django.urls import path, reverse
  15. from django.utils.decorators import method_decorator
  16. from django.utils.html import escape
  17. from django.utils.translation import gettext, gettext_lazy as _
  18. from django.views.decorators.csrf import csrf_protect
  19. from django.views.decorators.debug import sensitive_post_parameters
  20. csrf_protect_m = method_decorator(csrf_protect)
  21. sensitive_post_parameters_m = method_decorator(sensitive_post_parameters())
  22. @admin.register(Group)
  23. class GroupAdmin(admin.ModelAdmin):
  24. search_fields = ('name',)
  25. ordering = ('name',)
  26. filter_horizontal = ('permissions',)
  27. def formfield_for_manytomany(self, db_field, request=None, **kwargs):
  28. if db_field.name == 'permissions':
  29. qs = kwargs.get('queryset', db_field.remote_field.model.objects)
  30. # Avoid a major performance hit resolving permission names which
  31. # triggers a content_type load:
  32. kwargs['queryset'] = qs.select_related('content_type')
  33. return super().formfield_for_manytomany(db_field, request=request, **kwargs)
  34. @admin.register(User)
  35. class UserAdmin(admin.ModelAdmin):
  36. add_form_template = 'admin/auth/user/add_form.html'
  37. change_user_password_template = None
  38. fieldsets = (
  39. (None, {'fields': ('username', 'password')}),
  40. (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
  41. (_('Permissions'), {
  42. 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
  43. }),
  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', 'groups')
  57. search_fields = ('username', 'first_name', 'last_name', 'email')
  58. ordering = ('username',)
  59. filter_horizontal = ('groups', 'user_permissions',)
  60. def get_fieldsets(self, request, obj=None):
  61. if not obj:
  62. return self.add_fieldsets
  63. return super().get_fieldsets(request, obj)
  64. def get_form(self, request, obj=None, **kwargs):
  65. """
  66. Use special form during user creation
  67. """
  68. defaults = {}
  69. if obj is None:
  70. defaults['form'] = self.add_form
  71. defaults.update(kwargs)
  72. return super().get_form(request, obj, **defaults)
  73. def get_urls(self):
  74. return [
  75. path(
  76. '<id>/password/',
  77. self.admin_site.admin_view(self.user_change_password),
  78. name='auth_user_password_change',
  79. ),
  80. ] + super().get_urls()
  81. def lookup_allowed(self, lookup, value):
  82. # Don't allow lookups involving passwords.
  83. return not lookup.startswith('password') and super().lookup_allowed(lookup, value)
  84. @sensitive_post_parameters_m
  85. @csrf_protect_m
  86. def add_view(self, request, form_url='', extra_context=None):
  87. with transaction.atomic(using=router.db_for_write(self.model)):
  88. return self._add_view(request, form_url, extra_context)
  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. username_field = self.model._meta.get_field(self.model.USERNAME_FIELD)
  109. defaults = {
  110. 'auto_populated_fields': (),
  111. 'username_help_text': username_field.help_text,
  112. }
  113. extra_context.update(defaults)
  114. return super().add_view(request, form_url, extra_context)
  115. @sensitive_post_parameters_m
  116. def user_change_password(self, request, id, form_url=''):
  117. user = self.get_object(request, unquote(id))
  118. if not self.has_change_permission(request, user):
  119. raise PermissionDenied
  120. if user is None:
  121. raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
  122. 'name': self.model._meta.verbose_name,
  123. 'key': escape(id),
  124. })
  125. if request.method == 'POST':
  126. form = self.change_password_form(user, request.POST)
  127. if form.is_valid():
  128. form.save()
  129. change_message = self.construct_change_message(request, form, None)
  130. self.log_change(request, user, change_message)
  131. msg = gettext('Password changed successfully.')
  132. messages.success(request, msg)
  133. update_session_auth_hash(request, form.user)
  134. return HttpResponseRedirect(
  135. reverse(
  136. '%s:%s_%s_change' % (
  137. self.admin_site.name,
  138. user._meta.app_label,
  139. user._meta.model_name,
  140. ),
  141. args=(user.pk,),
  142. )
  143. )
  144. else:
  145. form = self.change_password_form(user)
  146. fieldsets = [(None, {'fields': list(form.base_fields)})]
  147. adminForm = admin.helpers.AdminForm(form, fieldsets, {})
  148. context = {
  149. 'title': _('Change password: %s') % escape(user.get_username()),
  150. 'adminForm': adminForm,
  151. 'form_url': form_url,
  152. 'form': form,
  153. 'is_popup': (IS_POPUP_VAR in request.POST or
  154. IS_POPUP_VAR in request.GET),
  155. 'add': True,
  156. 'change': False,
  157. 'has_delete_permission': False,
  158. 'has_change_permission': True,
  159. 'has_absolute_url': False,
  160. 'opts': self.model._meta,
  161. 'original': user,
  162. 'save_as': False,
  163. 'show_save': True,
  164. **self.admin_site.each_context(request),
  165. }
  166. request.current_app = self.admin_site.name
  167. return TemplateResponse(
  168. request,
  169. self.change_user_password_template or
  170. 'admin/auth/user/change_password.html',
  171. context,
  172. )
  173. def response_add(self, request, obj, post_url_continue=None):
  174. """
  175. Determine the HttpResponse for the add_view stage. It mostly defers to
  176. its superclass implementation but is customized because the User model
  177. has a slightly different workflow.
  178. """
  179. # We should allow further modification of the user just added i.e. the
  180. # 'Save' button should behave like the 'Save and continue editing'
  181. # button except in two scenarios:
  182. # * The user has pressed the 'Save and add another' button
  183. # * We are adding a user in a popup
  184. if '_addanother' not in request.POST and IS_POPUP_VAR not in request.POST:
  185. request.POST = request.POST.copy()
  186. request.POST['_continue'] = 1
  187. return super().response_add(request, obj, post_url_continue)