Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.8KB

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