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.

options.py 96KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507
  1. import copy
  2. import json
  3. import re
  4. from functools import partial, update_wrapper
  5. from urllib.parse import quote as urlquote
  6. from django import forms
  7. from django.conf import settings
  8. from django.contrib import messages
  9. from django.contrib.admin import helpers, widgets
  10. from django.contrib.admin.checks import (
  11. BaseModelAdminChecks,
  12. InlineModelAdminChecks,
  13. ModelAdminChecks,
  14. )
  15. from django.contrib.admin.decorators import display
  16. from django.contrib.admin.exceptions import DisallowedModelAdminToField
  17. from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
  18. from django.contrib.admin.utils import (
  19. NestedObjects,
  20. construct_change_message,
  21. flatten_fieldsets,
  22. get_deleted_objects,
  23. lookup_spawns_duplicates,
  24. model_format_dict,
  25. model_ngettext,
  26. quote,
  27. unquote,
  28. )
  29. from django.contrib.admin.widgets import AutocompleteSelect, AutocompleteSelectMultiple
  30. from django.contrib.auth import get_permission_codename
  31. from django.core.exceptions import (
  32. FieldDoesNotExist,
  33. FieldError,
  34. PermissionDenied,
  35. ValidationError,
  36. )
  37. from django.core.paginator import Paginator
  38. from django.db import models, router, transaction
  39. from django.db.models.constants import LOOKUP_SEP
  40. from django.forms.formsets import DELETION_FIELD_NAME, all_valid
  41. from django.forms.models import (
  42. BaseInlineFormSet,
  43. inlineformset_factory,
  44. modelform_defines_fields,
  45. modelform_factory,
  46. modelformset_factory,
  47. )
  48. from django.forms.widgets import CheckboxSelectMultiple, SelectMultiple
  49. from django.http import HttpResponseRedirect
  50. from django.http.response import HttpResponseBase
  51. from django.template.response import SimpleTemplateResponse, TemplateResponse
  52. from django.urls import reverse
  53. from django.utils.decorators import method_decorator
  54. from django.utils.html import format_html
  55. from django.utils.http import urlencode
  56. from django.utils.safestring import mark_safe
  57. from django.utils.text import (
  58. capfirst,
  59. format_lazy,
  60. get_text_list,
  61. smart_split,
  62. unescape_string_literal,
  63. )
  64. from django.utils.translation import gettext as _
  65. from django.utils.translation import ngettext
  66. from django.views.decorators.csrf import csrf_protect
  67. from django.views.generic import RedirectView
  68. IS_POPUP_VAR = "_popup"
  69. TO_FIELD_VAR = "_to_field"
  70. HORIZONTAL, VERTICAL = 1, 2
  71. def get_content_type_for_model(obj):
  72. # Since this module gets imported in the application's root package,
  73. # it cannot import models from other applications at the module level.
  74. from django.contrib.contenttypes.models import ContentType
  75. return ContentType.objects.get_for_model(obj, for_concrete_model=False)
  76. def get_ul_class(radio_style):
  77. return "radiolist" if radio_style == VERTICAL else "radiolist inline"
  78. class IncorrectLookupParameters(Exception):
  79. pass
  80. # Defaults for formfield_overrides. ModelAdmin subclasses can change this
  81. # by adding to ModelAdmin.formfield_overrides.
  82. FORMFIELD_FOR_DBFIELD_DEFAULTS = {
  83. models.DateTimeField: {
  84. "form_class": forms.SplitDateTimeField,
  85. "widget": widgets.AdminSplitDateTime,
  86. },
  87. models.DateField: {"widget": widgets.AdminDateWidget},
  88. models.TimeField: {"widget": widgets.AdminTimeWidget},
  89. models.TextField: {"widget": widgets.AdminTextareaWidget},
  90. models.URLField: {"widget": widgets.AdminURLFieldWidget},
  91. models.IntegerField: {"widget": widgets.AdminIntegerFieldWidget},
  92. models.BigIntegerField: {"widget": widgets.AdminBigIntegerFieldWidget},
  93. models.CharField: {"widget": widgets.AdminTextInputWidget},
  94. models.ImageField: {"widget": widgets.AdminFileWidget},
  95. models.FileField: {"widget": widgets.AdminFileWidget},
  96. models.EmailField: {"widget": widgets.AdminEmailInputWidget},
  97. models.UUIDField: {"widget": widgets.AdminUUIDInputWidget},
  98. }
  99. csrf_protect_m = method_decorator(csrf_protect)
  100. class BaseModelAdmin(metaclass=forms.MediaDefiningClass):
  101. """Functionality common to both ModelAdmin and InlineAdmin."""
  102. autocomplete_fields = ()
  103. raw_id_fields = ()
  104. fields = None
  105. exclude = None
  106. fieldsets = None
  107. form = forms.ModelForm
  108. filter_vertical = ()
  109. filter_horizontal = ()
  110. radio_fields = {}
  111. prepopulated_fields = {}
  112. formfield_overrides = {}
  113. readonly_fields = ()
  114. ordering = None
  115. sortable_by = None
  116. view_on_site = True
  117. show_full_result_count = True
  118. checks_class = BaseModelAdminChecks
  119. def check(self, **kwargs):
  120. return self.checks_class().check(self, **kwargs)
  121. def __init__(self):
  122. # Merge FORMFIELD_FOR_DBFIELD_DEFAULTS with the formfield_overrides
  123. # rather than simply overwriting.
  124. overrides = copy.deepcopy(FORMFIELD_FOR_DBFIELD_DEFAULTS)
  125. for k, v in self.formfield_overrides.items():
  126. overrides.setdefault(k, {}).update(v)
  127. self.formfield_overrides = overrides
  128. def formfield_for_dbfield(self, db_field, request, **kwargs):
  129. """
  130. Hook for specifying the form Field instance for a given database Field
  131. instance.
  132. If kwargs are given, they're passed to the form Field's constructor.
  133. """
  134. # If the field specifies choices, we don't need to look for special
  135. # admin widgets - we just need to use a select widget of some kind.
  136. if db_field.choices:
  137. return self.formfield_for_choice_field(db_field, request, **kwargs)
  138. # ForeignKey or ManyToManyFields
  139. if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
  140. # Combine the field kwargs with any options for formfield_overrides.
  141. # Make sure the passed in **kwargs override anything in
  142. # formfield_overrides because **kwargs is more specific, and should
  143. # always win.
  144. if db_field.__class__ in self.formfield_overrides:
  145. kwargs = {**self.formfield_overrides[db_field.__class__], **kwargs}
  146. # Get the correct formfield.
  147. if isinstance(db_field, models.ForeignKey):
  148. formfield = self.formfield_for_foreignkey(db_field, request, **kwargs)
  149. elif isinstance(db_field, models.ManyToManyField):
  150. formfield = self.formfield_for_manytomany(db_field, request, **kwargs)
  151. # For non-raw_id fields, wrap the widget with a wrapper that adds
  152. # extra HTML -- the "add other" interface -- to the end of the
  153. # rendered output. formfield can be None if it came from a
  154. # OneToOneField with parent_link=True or a M2M intermediary.
  155. if formfield and db_field.name not in self.raw_id_fields:
  156. related_modeladmin = self.admin_site._registry.get(
  157. db_field.remote_field.model
  158. )
  159. wrapper_kwargs = {}
  160. if related_modeladmin:
  161. wrapper_kwargs.update(
  162. can_add_related=related_modeladmin.has_add_permission(request),
  163. can_change_related=related_modeladmin.has_change_permission(
  164. request
  165. ),
  166. can_delete_related=related_modeladmin.has_delete_permission(
  167. request
  168. ),
  169. can_view_related=related_modeladmin.has_view_permission(
  170. request
  171. ),
  172. )
  173. formfield.widget = widgets.RelatedFieldWidgetWrapper(
  174. formfield.widget,
  175. db_field.remote_field,
  176. self.admin_site,
  177. **wrapper_kwargs,
  178. )
  179. return formfield
  180. # If we've got overrides for the formfield defined, use 'em. **kwargs
  181. # passed to formfield_for_dbfield override the defaults.
  182. for klass in db_field.__class__.mro():
  183. if klass in self.formfield_overrides:
  184. kwargs = {**copy.deepcopy(self.formfield_overrides[klass]), **kwargs}
  185. return db_field.formfield(**kwargs)
  186. # For any other type of field, just call its formfield() method.
  187. return db_field.formfield(**kwargs)
  188. def formfield_for_choice_field(self, db_field, request, **kwargs):
  189. """
  190. Get a form Field for a database Field that has declared choices.
  191. """
  192. # If the field is named as a radio_field, use a RadioSelect
  193. if db_field.name in self.radio_fields:
  194. # Avoid stomping on custom widget/choices arguments.
  195. if "widget" not in kwargs:
  196. kwargs["widget"] = widgets.AdminRadioSelect(
  197. attrs={
  198. "class": get_ul_class(self.radio_fields[db_field.name]),
  199. }
  200. )
  201. if "choices" not in kwargs:
  202. kwargs["choices"] = db_field.get_choices(
  203. include_blank=db_field.blank, blank_choice=[("", _("None"))]
  204. )
  205. return db_field.formfield(**kwargs)
  206. def get_field_queryset(self, db, db_field, request):
  207. """
  208. If the ModelAdmin specifies ordering, the queryset should respect that
  209. ordering. Otherwise don't specify the queryset, let the field decide
  210. (return None in that case).
  211. """
  212. related_admin = self.admin_site._registry.get(db_field.remote_field.model)
  213. if related_admin is not None:
  214. ordering = related_admin.get_ordering(request)
  215. if ordering is not None and ordering != ():
  216. return db_field.remote_field.model._default_manager.using(db).order_by(
  217. *ordering
  218. )
  219. return None
  220. def formfield_for_foreignkey(self, db_field, request, **kwargs):
  221. """
  222. Get a form Field for a ForeignKey.
  223. """
  224. db = kwargs.get("using")
  225. if "widget" not in kwargs:
  226. if db_field.name in self.get_autocomplete_fields(request):
  227. kwargs["widget"] = AutocompleteSelect(
  228. db_field, self.admin_site, using=db
  229. )
  230. elif db_field.name in self.raw_id_fields:
  231. kwargs["widget"] = widgets.ForeignKeyRawIdWidget(
  232. db_field.remote_field, self.admin_site, using=db
  233. )
  234. elif db_field.name in self.radio_fields:
  235. kwargs["widget"] = widgets.AdminRadioSelect(
  236. attrs={
  237. "class": get_ul_class(self.radio_fields[db_field.name]),
  238. }
  239. )
  240. kwargs["empty_label"] = (
  241. kwargs.get("empty_label", _("None")) if db_field.blank else None
  242. )
  243. if "queryset" not in kwargs:
  244. queryset = self.get_field_queryset(db, db_field, request)
  245. if queryset is not None:
  246. kwargs["queryset"] = queryset
  247. return db_field.formfield(**kwargs)
  248. def formfield_for_manytomany(self, db_field, request, **kwargs):
  249. """
  250. Get a form Field for a ManyToManyField.
  251. """
  252. # If it uses an intermediary model that isn't auto created, don't show
  253. # a field in admin.
  254. if not db_field.remote_field.through._meta.auto_created:
  255. return None
  256. db = kwargs.get("using")
  257. if "widget" not in kwargs:
  258. autocomplete_fields = self.get_autocomplete_fields(request)
  259. if db_field.name in autocomplete_fields:
  260. kwargs["widget"] = AutocompleteSelectMultiple(
  261. db_field,
  262. self.admin_site,
  263. using=db,
  264. )
  265. elif db_field.name in self.raw_id_fields:
  266. kwargs["widget"] = widgets.ManyToManyRawIdWidget(
  267. db_field.remote_field,
  268. self.admin_site,
  269. using=db,
  270. )
  271. elif db_field.name in [*self.filter_vertical, *self.filter_horizontal]:
  272. kwargs["widget"] = widgets.FilteredSelectMultiple(
  273. db_field.verbose_name, db_field.name in self.filter_vertical
  274. )
  275. if "queryset" not in kwargs:
  276. queryset = self.get_field_queryset(db, db_field, request)
  277. if queryset is not None:
  278. kwargs["queryset"] = queryset
  279. form_field = db_field.formfield(**kwargs)
  280. if isinstance(form_field.widget, SelectMultiple) and not isinstance(
  281. form_field.widget, (CheckboxSelectMultiple, AutocompleteSelectMultiple)
  282. ):
  283. msg = _(
  284. "Hold down “Control”, or “Command” on a Mac, to select more than one."
  285. )
  286. help_text = form_field.help_text
  287. form_field.help_text = (
  288. format_lazy("{} {}", help_text, msg) if help_text else msg
  289. )
  290. return form_field
  291. def get_autocomplete_fields(self, request):
  292. """
  293. Return a list of ForeignKey and/or ManyToMany fields which should use
  294. an autocomplete widget.
  295. """
  296. return self.autocomplete_fields
  297. def get_view_on_site_url(self, obj=None):
  298. if obj is None or not self.view_on_site:
  299. return None
  300. if callable(self.view_on_site):
  301. return self.view_on_site(obj)
  302. elif hasattr(obj, "get_absolute_url"):
  303. # use the ContentType lookup if view_on_site is True
  304. return reverse(
  305. "admin:view_on_site",
  306. kwargs={
  307. "content_type_id": get_content_type_for_model(obj).pk,
  308. "object_id": obj.pk,
  309. },
  310. current_app=self.admin_site.name,
  311. )
  312. def get_empty_value_display(self):
  313. """
  314. Return the empty_value_display set on ModelAdmin or AdminSite.
  315. """
  316. try:
  317. return mark_safe(self.empty_value_display)
  318. except AttributeError:
  319. return mark_safe(self.admin_site.empty_value_display)
  320. def get_exclude(self, request, obj=None):
  321. """
  322. Hook for specifying exclude.
  323. """
  324. return self.exclude
  325. def get_fields(self, request, obj=None):
  326. """
  327. Hook for specifying fields.
  328. """
  329. if self.fields:
  330. return self.fields
  331. # _get_form_for_get_fields() is implemented in subclasses.
  332. form = self._get_form_for_get_fields(request, obj)
  333. return [*form.base_fields, *self.get_readonly_fields(request, obj)]
  334. def get_fieldsets(self, request, obj=None):
  335. """
  336. Hook for specifying fieldsets.
  337. """
  338. if self.fieldsets:
  339. return self.fieldsets
  340. return [(None, {"fields": self.get_fields(request, obj)})]
  341. def get_inlines(self, request, obj):
  342. """Hook for specifying custom inlines."""
  343. return self.inlines
  344. def get_ordering(self, request):
  345. """
  346. Hook for specifying field ordering.
  347. """
  348. return self.ordering or () # otherwise we might try to *None, which is bad ;)
  349. def get_readonly_fields(self, request, obj=None):
  350. """
  351. Hook for specifying custom readonly fields.
  352. """
  353. return self.readonly_fields
  354. def get_prepopulated_fields(self, request, obj=None):
  355. """
  356. Hook for specifying custom prepopulated fields.
  357. """
  358. return self.prepopulated_fields
  359. def get_queryset(self, request):
  360. """
  361. Return a QuerySet of all model instances that can be edited by the
  362. admin site. This is used by changelist_view.
  363. """
  364. qs = self.model._default_manager.get_queryset()
  365. # TODO: this should be handled by some parameter to the ChangeList.
  366. ordering = self.get_ordering(request)
  367. if ordering:
  368. qs = qs.order_by(*ordering)
  369. return qs
  370. def get_sortable_by(self, request):
  371. """Hook for specifying which fields can be sorted in the changelist."""
  372. return (
  373. self.sortable_by
  374. if self.sortable_by is not None
  375. else self.get_list_display(request)
  376. )
  377. def lookup_allowed(self, lookup, value):
  378. from django.contrib.admin.filters import SimpleListFilter
  379. model = self.model
  380. # Check FKey lookups that are allowed, so that popups produced by
  381. # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
  382. # are allowed to work.
  383. for fk_lookup in model._meta.related_fkey_lookups:
  384. # As ``limit_choices_to`` can be a callable, invoke it here.
  385. if callable(fk_lookup):
  386. fk_lookup = fk_lookup()
  387. if (lookup, value) in widgets.url_params_from_lookup_dict(
  388. fk_lookup
  389. ).items():
  390. return True
  391. relation_parts = []
  392. prev_field = None
  393. for part in lookup.split(LOOKUP_SEP):
  394. try:
  395. field = model._meta.get_field(part)
  396. except FieldDoesNotExist:
  397. # Lookups on nonexistent fields are ok, since they're ignored
  398. # later.
  399. break
  400. # It is allowed to filter on values that would be found from local
  401. # model anyways. For example, if you filter on employee__department__id,
  402. # then the id value would be found already from employee__department_id.
  403. if not prev_field or (
  404. prev_field.is_relation
  405. and field not in prev_field.path_infos[-1].target_fields
  406. ):
  407. relation_parts.append(part)
  408. if not getattr(field, "path_infos", None):
  409. # This is not a relational field, so further parts
  410. # must be transforms.
  411. break
  412. prev_field = field
  413. model = field.path_infos[-1].to_opts.model
  414. if len(relation_parts) <= 1:
  415. # Either a local field filter, or no fields at all.
  416. return True
  417. valid_lookups = {self.date_hierarchy}
  418. for filter_item in self.list_filter:
  419. if isinstance(filter_item, type) and issubclass(
  420. filter_item, SimpleListFilter
  421. ):
  422. valid_lookups.add(filter_item.parameter_name)
  423. elif isinstance(filter_item, (list, tuple)):
  424. valid_lookups.add(filter_item[0])
  425. else:
  426. valid_lookups.add(filter_item)
  427. # Is it a valid relational lookup?
  428. return not {
  429. LOOKUP_SEP.join(relation_parts),
  430. LOOKUP_SEP.join(relation_parts + [part]),
  431. }.isdisjoint(valid_lookups)
  432. def to_field_allowed(self, request, to_field):
  433. """
  434. Return True if the model associated with this admin should be
  435. allowed to be referenced by the specified field.
  436. """
  437. opts = self.model._meta
  438. try:
  439. field = opts.get_field(to_field)
  440. except FieldDoesNotExist:
  441. return False
  442. # Always allow referencing the primary key since it's already possible
  443. # to get this information from the change view URL.
  444. if field.primary_key:
  445. return True
  446. # Allow reverse relationships to models defining m2m fields if they
  447. # target the specified field.
  448. for many_to_many in opts.many_to_many:
  449. if many_to_many.m2m_target_field_name() == to_field:
  450. return True
  451. # Make sure at least one of the models registered for this site
  452. # references this field through a FK or a M2M relationship.
  453. registered_models = set()
  454. for model, admin in self.admin_site._registry.items():
  455. registered_models.add(model)
  456. for inline in admin.inlines:
  457. registered_models.add(inline.model)
  458. related_objects = (
  459. f
  460. for f in opts.get_fields(include_hidden=True)
  461. if (f.auto_created and not f.concrete)
  462. )
  463. for related_object in related_objects:
  464. related_model = related_object.related_model
  465. remote_field = related_object.field.remote_field
  466. if (
  467. any(issubclass(model, related_model) for model in registered_models)
  468. and hasattr(remote_field, "get_related_field")
  469. and remote_field.get_related_field() == field
  470. ):
  471. return True
  472. return False
  473. def has_add_permission(self, request):
  474. """
  475. Return True if the given request has permission to add an object.
  476. Can be overridden by the user in subclasses.
  477. """
  478. opts = self.opts
  479. codename = get_permission_codename("add", opts)
  480. return request.user.has_perm("%s.%s" % (opts.app_label, codename))
  481. def has_change_permission(self, request, obj=None):
  482. """
  483. Return True if the given request has permission to change the given
  484. Django model instance, the default implementation doesn't examine the
  485. `obj` parameter.
  486. Can be overridden by the user in subclasses. In such case it should
  487. return True if the given request has permission to change the `obj`
  488. model instance. If `obj` is None, this should return True if the given
  489. request has permission to change *any* object of the given type.
  490. """
  491. opts = self.opts
  492. codename = get_permission_codename("change", opts)
  493. return request.user.has_perm("%s.%s" % (opts.app_label, codename))
  494. def has_delete_permission(self, request, obj=None):
  495. """
  496. Return True if the given request has permission to change the given
  497. Django model instance, the default implementation doesn't examine the
  498. `obj` parameter.
  499. Can be overridden by the user in subclasses. In such case it should
  500. return True if the given request has permission to delete the `obj`
  501. model instance. If `obj` is None, this should return True if the given
  502. request has permission to delete *any* object of the given type.
  503. """
  504. opts = self.opts
  505. codename = get_permission_codename("delete", opts)
  506. return request.user.has_perm("%s.%s" % (opts.app_label, codename))
  507. def has_view_permission(self, request, obj=None):
  508. """
  509. Return True if the given request has permission to view the given
  510. Django model instance. The default implementation doesn't examine the
  511. `obj` parameter.
  512. If overridden by the user in subclasses, it should return True if the
  513. given request has permission to view the `obj` model instance. If `obj`
  514. is None, it should return True if the request has permission to view
  515. any object of the given type.
  516. """
  517. opts = self.opts
  518. codename_view = get_permission_codename("view", opts)
  519. codename_change = get_permission_codename("change", opts)
  520. return request.user.has_perm(
  521. "%s.%s" % (opts.app_label, codename_view)
  522. ) or request.user.has_perm("%s.%s" % (opts.app_label, codename_change))
  523. def has_view_or_change_permission(self, request, obj=None):
  524. return self.has_view_permission(request, obj) or self.has_change_permission(
  525. request, obj
  526. )
  527. def has_module_permission(self, request):
  528. """
  529. Return True if the given request has any permission in the given
  530. app label.
  531. Can be overridden by the user in subclasses. In such case it should
  532. return True if the given request has permission to view the module on
  533. the admin index page and access the module's index page. Overriding it
  534. does not restrict access to the add, change or delete views. Use
  535. `ModelAdmin.has_(add|change|delete)_permission` for that.
  536. """
  537. return request.user.has_module_perms(self.opts.app_label)
  538. class ModelAdmin(BaseModelAdmin):
  539. """Encapsulate all admin options and functionality for a given model."""
  540. list_display = ("__str__",)
  541. list_display_links = ()
  542. list_filter = ()
  543. list_select_related = False
  544. list_per_page = 100
  545. list_max_show_all = 200
  546. list_editable = ()
  547. search_fields = ()
  548. search_help_text = None
  549. date_hierarchy = None
  550. save_as = False
  551. save_as_continue = True
  552. save_on_top = False
  553. paginator = Paginator
  554. preserve_filters = True
  555. inlines = ()
  556. # Custom templates (designed to be over-ridden in subclasses)
  557. add_form_template = None
  558. change_form_template = None
  559. change_list_template = None
  560. delete_confirmation_template = None
  561. delete_selected_confirmation_template = None
  562. object_history_template = None
  563. popup_response_template = None
  564. # Actions
  565. actions = ()
  566. action_form = helpers.ActionForm
  567. actions_on_top = True
  568. actions_on_bottom = False
  569. actions_selection_counter = True
  570. checks_class = ModelAdminChecks
  571. def __init__(self, model, admin_site):
  572. self.model = model
  573. self.opts = model._meta
  574. self.admin_site = admin_site
  575. super().__init__()
  576. def __str__(self):
  577. return "%s.%s" % (self.model._meta.app_label, self.__class__.__name__)
  578. def __repr__(self):
  579. return (
  580. f"<{self.__class__.__qualname__}: model={self.model.__qualname__} "
  581. f"site={self.admin_site!r}>"
  582. )
  583. def get_inline_instances(self, request, obj=None):
  584. inline_instances = []
  585. for inline_class in self.get_inlines(request, obj):
  586. inline = inline_class(self.model, self.admin_site)
  587. if request:
  588. if not (
  589. inline.has_view_or_change_permission(request, obj)
  590. or inline.has_add_permission(request, obj)
  591. or inline.has_delete_permission(request, obj)
  592. ):
  593. continue
  594. if not inline.has_add_permission(request, obj):
  595. inline.max_num = 0
  596. inline_instances.append(inline)
  597. return inline_instances
  598. def get_urls(self):
  599. from django.urls import path
  600. def wrap(view):
  601. def wrapper(*args, **kwargs):
  602. return self.admin_site.admin_view(view)(*args, **kwargs)
  603. wrapper.model_admin = self
  604. return update_wrapper(wrapper, view)
  605. info = self.model._meta.app_label, self.model._meta.model_name
  606. return [
  607. path("", wrap(self.changelist_view), name="%s_%s_changelist" % info),
  608. path("add/", wrap(self.add_view), name="%s_%s_add" % info),
  609. path(
  610. "<path:object_id>/history/",
  611. wrap(self.history_view),
  612. name="%s_%s_history" % info,
  613. ),
  614. path(
  615. "<path:object_id>/delete/",
  616. wrap(self.delete_view),
  617. name="%s_%s_delete" % info,
  618. ),
  619. path(
  620. "<path:object_id>/change/",
  621. wrap(self.change_view),
  622. name="%s_%s_change" % info,
  623. ),
  624. # For backwards compatibility (was the change url before 1.9)
  625. path(
  626. "<path:object_id>/",
  627. wrap(
  628. RedirectView.as_view(
  629. pattern_name="%s:%s_%s_change"
  630. % ((self.admin_site.name,) + info)
  631. )
  632. ),
  633. ),
  634. ]
  635. @property
  636. def urls(self):
  637. return self.get_urls()
  638. @property
  639. def media(self):
  640. extra = "" if settings.DEBUG else ".min"
  641. js = [
  642. "vendor/jquery/jquery%s.js" % extra,
  643. "jquery.init.js",
  644. "core.js",
  645. "admin/RelatedObjectLookups.js",
  646. "actions.js",
  647. "urlify.js",
  648. "prepopulate.js",
  649. "vendor/xregexp/xregexp%s.js" % extra,
  650. ]
  651. return forms.Media(js=["admin/js/%s" % url for url in js])
  652. def get_model_perms(self, request):
  653. """
  654. Return a dict of all perms for this model. This dict has the keys
  655. ``add``, ``change``, ``delete``, and ``view`` mapping to the True/False
  656. for each of those actions.
  657. """
  658. return {
  659. "add": self.has_add_permission(request),
  660. "change": self.has_change_permission(request),
  661. "delete": self.has_delete_permission(request),
  662. "view": self.has_view_permission(request),
  663. }
  664. def _get_form_for_get_fields(self, request, obj):
  665. return self.get_form(request, obj, fields=None)
  666. def get_form(self, request, obj=None, change=False, **kwargs):
  667. """
  668. Return a Form class for use in the admin add view. This is used by
  669. add_view and change_view.
  670. """
  671. if "fields" in kwargs:
  672. fields = kwargs.pop("fields")
  673. else:
  674. fields = flatten_fieldsets(self.get_fieldsets(request, obj))
  675. excluded = self.get_exclude(request, obj)
  676. exclude = [] if excluded is None else list(excluded)
  677. readonly_fields = self.get_readonly_fields(request, obj)
  678. exclude.extend(readonly_fields)
  679. # Exclude all fields if it's a change form and the user doesn't have
  680. # the change permission.
  681. if (
  682. change
  683. and hasattr(request, "user")
  684. and not self.has_change_permission(request, obj)
  685. ):
  686. exclude.extend(fields)
  687. if excluded is None and hasattr(self.form, "_meta") and self.form._meta.exclude:
  688. # Take the custom ModelForm's Meta.exclude into account only if the
  689. # ModelAdmin doesn't define its own.
  690. exclude.extend(self.form._meta.exclude)
  691. # if exclude is an empty list we pass None to be consistent with the
  692. # default on modelform_factory
  693. exclude = exclude or None
  694. # Remove declared form fields which are in readonly_fields.
  695. new_attrs = dict.fromkeys(
  696. f for f in readonly_fields if f in self.form.declared_fields
  697. )
  698. form = type(self.form.__name__, (self.form,), new_attrs)
  699. defaults = {
  700. "form": form,
  701. "fields": fields,
  702. "exclude": exclude,
  703. "formfield_callback": partial(self.formfield_for_dbfield, request=request),
  704. **kwargs,
  705. }
  706. if defaults["fields"] is None and not modelform_defines_fields(
  707. defaults["form"]
  708. ):
  709. defaults["fields"] = forms.ALL_FIELDS
  710. try:
  711. return modelform_factory(self.model, **defaults)
  712. except FieldError as e:
  713. raise FieldError(
  714. "%s. Check fields/fieldsets/exclude attributes of class %s."
  715. % (e, self.__class__.__name__)
  716. )
  717. def get_changelist(self, request, **kwargs):
  718. """
  719. Return the ChangeList class for use on the changelist page.
  720. """
  721. from django.contrib.admin.views.main import ChangeList
  722. return ChangeList
  723. def get_changelist_instance(self, request):
  724. """
  725. Return a `ChangeList` instance based on `request`. May raise
  726. `IncorrectLookupParameters`.
  727. """
  728. list_display = self.get_list_display(request)
  729. list_display_links = self.get_list_display_links(request, list_display)
  730. # Add the action checkboxes if any actions are available.
  731. if self.get_actions(request):
  732. list_display = ["action_checkbox", *list_display]
  733. sortable_by = self.get_sortable_by(request)
  734. ChangeList = self.get_changelist(request)
  735. return ChangeList(
  736. request,
  737. self.model,
  738. list_display,
  739. list_display_links,
  740. self.get_list_filter(request),
  741. self.date_hierarchy,
  742. self.get_search_fields(request),
  743. self.get_list_select_related(request),
  744. self.list_per_page,
  745. self.list_max_show_all,
  746. self.list_editable,
  747. self,
  748. sortable_by,
  749. self.search_help_text,
  750. )
  751. def get_object(self, request, object_id, from_field=None):
  752. """
  753. Return an instance matching the field and value provided, the primary
  754. key is used if no field is provided. Return ``None`` if no match is
  755. found or the object_id fails validation.
  756. """
  757. queryset = self.get_queryset(request)
  758. model = queryset.model
  759. field = (
  760. model._meta.pk if from_field is None else model._meta.get_field(from_field)
  761. )
  762. try:
  763. object_id = field.to_python(object_id)
  764. return queryset.get(**{field.name: object_id})
  765. except (model.DoesNotExist, ValidationError, ValueError):
  766. return None
  767. def get_changelist_form(self, request, **kwargs):
  768. """
  769. Return a Form class for use in the Formset on the changelist page.
  770. """
  771. defaults = {
  772. "formfield_callback": partial(self.formfield_for_dbfield, request=request),
  773. **kwargs,
  774. }
  775. if defaults.get("fields") is None and not modelform_defines_fields(
  776. defaults.get("form")
  777. ):
  778. defaults["fields"] = forms.ALL_FIELDS
  779. return modelform_factory(self.model, **defaults)
  780. def get_changelist_formset(self, request, **kwargs):
  781. """
  782. Return a FormSet class for use on the changelist page if list_editable
  783. is used.
  784. """
  785. defaults = {
  786. "formfield_callback": partial(self.formfield_for_dbfield, request=request),
  787. **kwargs,
  788. }
  789. return modelformset_factory(
  790. self.model,
  791. self.get_changelist_form(request),
  792. extra=0,
  793. fields=self.list_editable,
  794. **defaults,
  795. )
  796. def get_formsets_with_inlines(self, request, obj=None):
  797. """
  798. Yield formsets and the corresponding inlines.
  799. """
  800. for inline in self.get_inline_instances(request, obj):
  801. yield inline.get_formset(request, obj), inline
  802. def get_paginator(
  803. self, request, queryset, per_page, orphans=0, allow_empty_first_page=True
  804. ):
  805. return self.paginator(queryset, per_page, orphans, allow_empty_first_page)
  806. def log_addition(self, request, obj, message):
  807. """
  808. Log that an object has been successfully added.
  809. The default implementation creates an admin LogEntry object.
  810. """
  811. from django.contrib.admin.models import ADDITION, LogEntry
  812. return LogEntry.objects.log_action(
  813. user_id=request.user.pk,
  814. content_type_id=get_content_type_for_model(obj).pk,
  815. object_id=obj.pk,
  816. object_repr=str(obj),
  817. action_flag=ADDITION,
  818. change_message=message,
  819. )
  820. def log_change(self, request, obj, message):
  821. """
  822. Log that an object has been successfully changed.
  823. The default implementation creates an admin LogEntry object.
  824. """
  825. from django.contrib.admin.models import CHANGE, LogEntry
  826. return LogEntry.objects.log_action(
  827. user_id=request.user.pk,
  828. content_type_id=get_content_type_for_model(obj).pk,
  829. object_id=obj.pk,
  830. object_repr=str(obj),
  831. action_flag=CHANGE,
  832. change_message=message,
  833. )
  834. def log_deletion(self, request, obj, object_repr):
  835. """
  836. Log that an object will be deleted. Note that this method must be
  837. called before the deletion.
  838. The default implementation creates an admin LogEntry object.
  839. """
  840. from django.contrib.admin.models import DELETION, LogEntry
  841. return LogEntry.objects.log_action(
  842. user_id=request.user.pk,
  843. content_type_id=get_content_type_for_model(obj).pk,
  844. object_id=obj.pk,
  845. object_repr=object_repr,
  846. action_flag=DELETION,
  847. )
  848. @display(description=mark_safe('<input type="checkbox" id="action-toggle">'))
  849. def action_checkbox(self, obj):
  850. """
  851. A list_display column containing a checkbox widget.
  852. """
  853. return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, str(obj.pk))
  854. @staticmethod
  855. def _get_action_description(func, name):
  856. return getattr(func, "short_description", capfirst(name.replace("_", " ")))
  857. def _get_base_actions(self):
  858. """Return the list of actions, prior to any request-based filtering."""
  859. actions = []
  860. base_actions = (self.get_action(action) for action in self.actions or [])
  861. # get_action might have returned None, so filter any of those out.
  862. base_actions = [action for action in base_actions if action]
  863. base_action_names = {name for _, name, _ in base_actions}
  864. # Gather actions from the admin site first
  865. for name, func in self.admin_site.actions:
  866. if name in base_action_names:
  867. continue
  868. description = self._get_action_description(func, name)
  869. actions.append((func, name, description))
  870. # Add actions from this ModelAdmin.
  871. actions.extend(base_actions)
  872. return actions
  873. def _filter_actions_by_permissions(self, request, actions):
  874. """Filter out any actions that the user doesn't have access to."""
  875. filtered_actions = []
  876. for action in actions:
  877. callable = action[0]
  878. if not hasattr(callable, "allowed_permissions"):
  879. filtered_actions.append(action)
  880. continue
  881. permission_checks = (
  882. getattr(self, "has_%s_permission" % permission)
  883. for permission in callable.allowed_permissions
  884. )
  885. if any(has_permission(request) for has_permission in permission_checks):
  886. filtered_actions.append(action)
  887. return filtered_actions
  888. def get_actions(self, request):
  889. """
  890. Return a dictionary mapping the names of all actions for this
  891. ModelAdmin to a tuple of (callable, name, description) for each action.
  892. """
  893. # If self.actions is set to None that means actions are disabled on
  894. # this page.
  895. if self.actions is None or IS_POPUP_VAR in request.GET:
  896. return {}
  897. actions = self._filter_actions_by_permissions(request, self._get_base_actions())
  898. return {name: (func, name, desc) for func, name, desc in actions}
  899. def get_action_choices(self, request, default_choices=models.BLANK_CHOICE_DASH):
  900. """
  901. Return a list of choices for use in a form object. Each choice is a
  902. tuple (name, description).
  903. """
  904. choices = [] + default_choices
  905. for func, name, description in self.get_actions(request).values():
  906. choice = (name, description % model_format_dict(self.opts))
  907. choices.append(choice)
  908. return choices
  909. def get_action(self, action):
  910. """
  911. Return a given action from a parameter, which can either be a callable,
  912. or the name of a method on the ModelAdmin. Return is a tuple of
  913. (callable, name, description).
  914. """
  915. # If the action is a callable, just use it.
  916. if callable(action):
  917. func = action
  918. action = action.__name__
  919. # Next, look for a method. Grab it off self.__class__ to get an unbound
  920. # method instead of a bound one; this ensures that the calling
  921. # conventions are the same for functions and methods.
  922. elif hasattr(self.__class__, action):
  923. func = getattr(self.__class__, action)
  924. # Finally, look for a named method on the admin site
  925. else:
  926. try:
  927. func = self.admin_site.get_action(action)
  928. except KeyError:
  929. return None
  930. description = self._get_action_description(func, action)
  931. return func, action, description
  932. def get_list_display(self, request):
  933. """
  934. Return a sequence containing the fields to be displayed on the
  935. changelist.
  936. """
  937. return self.list_display
  938. def get_list_display_links(self, request, list_display):
  939. """
  940. Return a sequence containing the fields to be displayed as links
  941. on the changelist. The list_display parameter is the list of fields
  942. returned by get_list_display().
  943. """
  944. if (
  945. self.list_display_links
  946. or self.list_display_links is None
  947. or not list_display
  948. ):
  949. return self.list_display_links
  950. else:
  951. # Use only the first item in list_display as link
  952. return list(list_display)[:1]
  953. def get_list_filter(self, request):
  954. """
  955. Return a sequence containing the fields to be displayed as filters in
  956. the right sidebar of the changelist page.
  957. """
  958. return self.list_filter
  959. def get_list_select_related(self, request):
  960. """
  961. Return a list of fields to add to the select_related() part of the
  962. changelist items query.
  963. """
  964. return self.list_select_related
  965. def get_search_fields(self, request):
  966. """
  967. Return a sequence containing the fields to be searched whenever
  968. somebody submits a search query.
  969. """
  970. return self.search_fields
  971. def get_search_results(self, request, queryset, search_term):
  972. """
  973. Return a tuple containing a queryset to implement the search
  974. and a boolean indicating if the results may contain duplicates.
  975. """
  976. # Apply keyword searches.
  977. def construct_search(field_name):
  978. if field_name.startswith("^"):
  979. return "%s__istartswith" % field_name[1:]
  980. elif field_name.startswith("="):
  981. return "%s__iexact" % field_name[1:]
  982. elif field_name.startswith("@"):
  983. return "%s__search" % field_name[1:]
  984. # Use field_name if it includes a lookup.
  985. opts = queryset.model._meta
  986. lookup_fields = field_name.split(LOOKUP_SEP)
  987. # Go through the fields, following all relations.
  988. prev_field = None
  989. for path_part in lookup_fields:
  990. if path_part == "pk":
  991. path_part = opts.pk.name
  992. try:
  993. field = opts.get_field(path_part)
  994. except FieldDoesNotExist:
  995. # Use valid query lookups.
  996. if prev_field and prev_field.get_lookup(path_part):
  997. return field_name
  998. else:
  999. prev_field = field
  1000. if hasattr(field, "path_infos"):
  1001. # Update opts to follow the relation.
  1002. opts = field.path_infos[-1].to_opts
  1003. # Otherwise, use the field with icontains.
  1004. return "%s__icontains" % field_name
  1005. may_have_duplicates = False
  1006. search_fields = self.get_search_fields(request)
  1007. if search_fields and search_term:
  1008. orm_lookups = [
  1009. construct_search(str(search_field)) for search_field in search_fields
  1010. ]
  1011. term_queries = []
  1012. for bit in smart_split(search_term):
  1013. if bit.startswith(('"', "'")) and bit[0] == bit[-1]:
  1014. bit = unescape_string_literal(bit)
  1015. or_queries = models.Q(
  1016. *((orm_lookup, bit) for orm_lookup in orm_lookups),
  1017. _connector=models.Q.OR,
  1018. )
  1019. term_queries.append(or_queries)
  1020. queryset = queryset.filter(models.Q(*term_queries))
  1021. may_have_duplicates |= any(
  1022. lookup_spawns_duplicates(self.opts, search_spec)
  1023. for search_spec in orm_lookups
  1024. )
  1025. return queryset, may_have_duplicates
  1026. def get_preserved_filters(self, request):
  1027. """
  1028. Return the preserved filters querystring.
  1029. """
  1030. match = request.resolver_match
  1031. if self.preserve_filters and match:
  1032. opts = self.model._meta
  1033. current_url = "%s:%s" % (match.app_name, match.url_name)
  1034. changelist_url = "admin:%s_%s_changelist" % (
  1035. opts.app_label,
  1036. opts.model_name,
  1037. )
  1038. if current_url == changelist_url:
  1039. preserved_filters = request.GET.urlencode()
  1040. else:
  1041. preserved_filters = request.GET.get("_changelist_filters")
  1042. if preserved_filters:
  1043. return urlencode({"_changelist_filters": preserved_filters})
  1044. return ""
  1045. def construct_change_message(self, request, form, formsets, add=False):
  1046. """
  1047. Construct a JSON structure describing changes from a changed object.
  1048. """
  1049. return construct_change_message(form, formsets, add)
  1050. def message_user(
  1051. self, request, message, level=messages.INFO, extra_tags="", fail_silently=False
  1052. ):
  1053. """
  1054. Send a message to the user. The default implementation
  1055. posts a message using the django.contrib.messages backend.
  1056. Exposes almost the same API as messages.add_message(), but accepts the
  1057. positional arguments in a different order to maintain backwards
  1058. compatibility. For convenience, it accepts the `level` argument as
  1059. a string rather than the usual level number.
  1060. """
  1061. if not isinstance(level, int):
  1062. # attempt to get the level if passed a string
  1063. try:
  1064. level = getattr(messages.constants, level.upper())
  1065. except AttributeError:
  1066. levels = messages.constants.DEFAULT_TAGS.values()
  1067. levels_repr = ", ".join("`%s`" % level for level in levels)
  1068. raise ValueError(
  1069. "Bad message level string: `%s`. Possible values are: %s"
  1070. % (level, levels_repr)
  1071. )
  1072. messages.add_message(
  1073. request, level, message, extra_tags=extra_tags, fail_silently=fail_silently
  1074. )
  1075. def save_form(self, request, form, change):
  1076. """
  1077. Given a ModelForm return an unsaved instance. ``change`` is True if
  1078. the object is being changed, and False if it's being added.
  1079. """
  1080. return form.save(commit=False)
  1081. def save_model(self, request, obj, form, change):
  1082. """
  1083. Given a model instance save it to the database.
  1084. """
  1085. obj.save()
  1086. def delete_model(self, request, obj):
  1087. """
  1088. Given a model instance delete it from the database.
  1089. """
  1090. obj.delete()
  1091. def delete_queryset(self, request, queryset):
  1092. """Given a queryset, delete it from the database."""
  1093. queryset.delete()
  1094. def save_formset(self, request, form, formset, change):
  1095. """
  1096. Given an inline formset save it to the database.
  1097. """
  1098. formset.save()
  1099. def save_related(self, request, form, formsets, change):
  1100. """
  1101. Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
  1102. list of inline formsets and a boolean value based on whether the
  1103. parent is being added or changed, save the related objects to the
  1104. database. Note that at this point save_form() and save_model() have
  1105. already been called.
  1106. """
  1107. form.save_m2m()
  1108. for formset in formsets:
  1109. self.save_formset(request, form, formset, change=change)
  1110. def render_change_form(
  1111. self, request, context, add=False, change=False, form_url="", obj=None
  1112. ):
  1113. opts = self.model._meta
  1114. app_label = opts.app_label
  1115. preserved_filters = self.get_preserved_filters(request)
  1116. form_url = add_preserved_filters(
  1117. {"preserved_filters": preserved_filters, "opts": opts}, form_url
  1118. )
  1119. view_on_site_url = self.get_view_on_site_url(obj)
  1120. has_editable_inline_admin_formsets = False
  1121. for inline in context["inline_admin_formsets"]:
  1122. if (
  1123. inline.has_add_permission
  1124. or inline.has_change_permission
  1125. or inline.has_delete_permission
  1126. ):
  1127. has_editable_inline_admin_formsets = True
  1128. break
  1129. context.update(
  1130. {
  1131. "add": add,
  1132. "change": change,
  1133. "has_view_permission": self.has_view_permission(request, obj),
  1134. "has_add_permission": self.has_add_permission(request),
  1135. "has_change_permission": self.has_change_permission(request, obj),
  1136. "has_delete_permission": self.has_delete_permission(request, obj),
  1137. "has_editable_inline_admin_formsets": (
  1138. has_editable_inline_admin_formsets
  1139. ),
  1140. "has_file_field": context["adminform"].form.is_multipart()
  1141. or any(
  1142. admin_formset.formset.is_multipart()
  1143. for admin_formset in context["inline_admin_formsets"]
  1144. ),
  1145. "has_absolute_url": view_on_site_url is not None,
  1146. "absolute_url": view_on_site_url,
  1147. "form_url": form_url,
  1148. "opts": opts,
  1149. "content_type_id": get_content_type_for_model(self.model).pk,
  1150. "save_as": self.save_as,
  1151. "save_on_top": self.save_on_top,
  1152. "to_field_var": TO_FIELD_VAR,
  1153. "is_popup_var": IS_POPUP_VAR,
  1154. "app_label": app_label,
  1155. }
  1156. )
  1157. if add and self.add_form_template is not None:
  1158. form_template = self.add_form_template
  1159. else:
  1160. form_template = self.change_form_template
  1161. request.current_app = self.admin_site.name
  1162. return TemplateResponse(
  1163. request,
  1164. form_template
  1165. or [
  1166. "admin/%s/%s/change_form.html" % (app_label, opts.model_name),
  1167. "admin/%s/change_form.html" % app_label,
  1168. "admin/change_form.html",
  1169. ],
  1170. context,
  1171. )
  1172. def response_add(self, request, obj, post_url_continue=None):
  1173. """
  1174. Determine the HttpResponse for the add_view stage.
  1175. """
  1176. opts = obj._meta
  1177. preserved_filters = self.get_preserved_filters(request)
  1178. obj_url = reverse(
  1179. "admin:%s_%s_change" % (opts.app_label, opts.model_name),
  1180. args=(quote(obj.pk),),
  1181. current_app=self.admin_site.name,
  1182. )
  1183. # Add a link to the object's change form if the user can edit the obj.
  1184. if self.has_change_permission(request, obj):
  1185. obj_repr = format_html('<a href="{}">{}</a>', urlquote(obj_url), obj)
  1186. else:
  1187. obj_repr = str(obj)
  1188. msg_dict = {
  1189. "name": opts.verbose_name,
  1190. "obj": obj_repr,
  1191. }
  1192. # Here, we distinguish between different save types by checking for
  1193. # the presence of keys in request.POST.
  1194. if IS_POPUP_VAR in request.POST:
  1195. to_field = request.POST.get(TO_FIELD_VAR)
  1196. if to_field:
  1197. attr = str(to_field)
  1198. else:
  1199. attr = obj._meta.pk.attname
  1200. value = obj.serializable_value(attr)
  1201. popup_response_data = json.dumps(
  1202. {
  1203. "value": str(value),
  1204. "obj": str(obj),
  1205. }
  1206. )
  1207. return TemplateResponse(
  1208. request,
  1209. self.popup_response_template
  1210. or [
  1211. "admin/%s/%s/popup_response.html"
  1212. % (opts.app_label, opts.model_name),
  1213. "admin/%s/popup_response.html" % opts.app_label,
  1214. "admin/popup_response.html",
  1215. ],
  1216. {
  1217. "popup_response_data": popup_response_data,
  1218. },
  1219. )
  1220. elif "_continue" in request.POST or (
  1221. # Redirecting after "Save as new".
  1222. "_saveasnew" in request.POST
  1223. and self.save_as_continue
  1224. and self.has_change_permission(request, obj)
  1225. ):
  1226. msg = _("The {name} “{obj}” was added successfully.")
  1227. if self.has_change_permission(request, obj):
  1228. msg += " " + _("You may edit it again below.")
  1229. self.message_user(request, format_html(msg, **msg_dict), messages.SUCCESS)
  1230. if post_url_continue is None:
  1231. post_url_continue = obj_url
  1232. post_url_continue = add_preserved_filters(
  1233. {"preserved_filters": preserved_filters, "opts": opts},
  1234. post_url_continue,
  1235. )
  1236. return HttpResponseRedirect(post_url_continue)
  1237. elif "_addanother" in request.POST:
  1238. msg = format_html(
  1239. _(
  1240. "The {name} “{obj}” was added successfully. You may add another "
  1241. "{name} below."
  1242. ),
  1243. **msg_dict,
  1244. )
  1245. self.message_user(request, msg, messages.SUCCESS)
  1246. redirect_url = request.path
  1247. redirect_url = add_preserved_filters(
  1248. {"preserved_filters": preserved_filters, "opts": opts}, redirect_url
  1249. )
  1250. return HttpResponseRedirect(redirect_url)
  1251. else:
  1252. msg = format_html(
  1253. _("The {name} “{obj}” was added successfully."), **msg_dict
  1254. )
  1255. self.message_user(request, msg, messages.SUCCESS)
  1256. return self.response_post_save_add(request, obj)
  1257. def response_change(self, request, obj):
  1258. """
  1259. Determine the HttpResponse for the change_view stage.
  1260. """
  1261. if IS_POPUP_VAR in request.POST:
  1262. opts = obj._meta
  1263. to_field = request.POST.get(TO_FIELD_VAR)
  1264. attr = str(to_field) if to_field else opts.pk.attname
  1265. value = request.resolver_match.kwargs["object_id"]
  1266. new_value = obj.serializable_value(attr)
  1267. popup_response_data = json.dumps(
  1268. {
  1269. "action": "change",
  1270. "value": str(value),
  1271. "obj": str(obj),
  1272. "new_value": str(new_value),
  1273. }
  1274. )
  1275. return TemplateResponse(
  1276. request,
  1277. self.popup_response_template
  1278. or [
  1279. "admin/%s/%s/popup_response.html"
  1280. % (opts.app_label, opts.model_name),
  1281. "admin/%s/popup_response.html" % opts.app_label,
  1282. "admin/popup_response.html",
  1283. ],
  1284. {
  1285. "popup_response_data": popup_response_data,
  1286. },
  1287. )
  1288. opts = self.model._meta
  1289. preserved_filters = self.get_preserved_filters(request)
  1290. msg_dict = {
  1291. "name": opts.verbose_name,
  1292. "obj": format_html('<a href="{}">{}</a>', urlquote(request.path), obj),
  1293. }
  1294. if "_continue" in request.POST:
  1295. msg = format_html(
  1296. _(
  1297. "The {name} “{obj}” was changed successfully. You may edit it "
  1298. "again below."
  1299. ),
  1300. **msg_dict,
  1301. )
  1302. self.message_user(request, msg, messages.SUCCESS)
  1303. redirect_url = request.path
  1304. redirect_url = add_preserved_filters(
  1305. {"preserved_filters": preserved_filters, "opts": opts}, redirect_url
  1306. )
  1307. return HttpResponseRedirect(redirect_url)
  1308. elif "_saveasnew" in request.POST:
  1309. msg = format_html(
  1310. _(
  1311. "The {name} “{obj}” was added successfully. You may edit it again "
  1312. "below."
  1313. ),
  1314. **msg_dict,
  1315. )
  1316. self.message_user(request, msg, messages.SUCCESS)
  1317. redirect_url = reverse(
  1318. "admin:%s_%s_change" % (opts.app_label, opts.model_name),
  1319. args=(obj.pk,),
  1320. current_app=self.admin_site.name,
  1321. )
  1322. redirect_url = add_preserved_filters(
  1323. {"preserved_filters": preserved_filters, "opts": opts}, redirect_url
  1324. )
  1325. return HttpResponseRedirect(redirect_url)
  1326. elif "_addanother" in request.POST:
  1327. msg = format_html(
  1328. _(
  1329. "The {name} “{obj}” was changed successfully. You may add another "
  1330. "{name} below."
  1331. ),
  1332. **msg_dict,
  1333. )
  1334. self.message_user(request, msg, messages.SUCCESS)
  1335. redirect_url = reverse(
  1336. "admin:%s_%s_add" % (opts.app_label, opts.model_name),
  1337. current_app=self.admin_site.name,
  1338. )
  1339. redirect_url = add_preserved_filters(
  1340. {"preserved_filters": preserved_filters, "opts": opts}, redirect_url
  1341. )
  1342. return HttpResponseRedirect(redirect_url)
  1343. else:
  1344. msg = format_html(
  1345. _("The {name} “{obj}” was changed successfully."), **msg_dict
  1346. )
  1347. self.message_user(request, msg, messages.SUCCESS)
  1348. return self.response_post_save_change(request, obj)
  1349. def _response_post_save(self, request, obj):
  1350. opts = self.model._meta
  1351. if self.has_view_or_change_permission(request):
  1352. post_url = reverse(
  1353. "admin:%s_%s_changelist" % (opts.app_label, opts.model_name),
  1354. current_app=self.admin_site.name,
  1355. )
  1356. preserved_filters = self.get_preserved_filters(request)
  1357. post_url = add_preserved_filters(
  1358. {"preserved_filters": preserved_filters, "opts": opts}, post_url
  1359. )
  1360. else:
  1361. post_url = reverse("admin:index", current_app=self.admin_site.name)
  1362. return HttpResponseRedirect(post_url)
  1363. def response_post_save_add(self, request, obj):
  1364. """
  1365. Figure out where to redirect after the 'Save' button has been pressed
  1366. when adding a new object.
  1367. """
  1368. return self._response_post_save(request, obj)
  1369. def response_post_save_change(self, request, obj):
  1370. """
  1371. Figure out where to redirect after the 'Save' button has been pressed
  1372. when editing an existing object.
  1373. """
  1374. return self._response_post_save(request, obj)
  1375. def response_action(self, request, queryset):
  1376. """
  1377. Handle an admin action. This is called if a request is POSTed to the
  1378. changelist; it returns an HttpResponse if the action was handled, and
  1379. None otherwise.
  1380. """
  1381. # There can be multiple action forms on the page (at the top
  1382. # and bottom of the change list, for example). Get the action
  1383. # whose button was pushed.
  1384. try:
  1385. action_index = int(request.POST.get("index", 0))
  1386. except ValueError:
  1387. action_index = 0
  1388. # Construct the action form.
  1389. data = request.POST.copy()
  1390. data.pop(helpers.ACTION_CHECKBOX_NAME, None)
  1391. data.pop("index", None)
  1392. # Use the action whose button was pushed
  1393. try:
  1394. data.update({"action": data.getlist("action")[action_index]})
  1395. except IndexError:
  1396. # If we didn't get an action from the chosen form that's invalid
  1397. # POST data, so by deleting action it'll fail the validation check
  1398. # below. So no need to do anything here
  1399. pass
  1400. action_form = self.action_form(data, auto_id=None)
  1401. action_form.fields["action"].choices = self.get_action_choices(request)
  1402. # If the form's valid we can handle the action.
  1403. if action_form.is_valid():
  1404. action = action_form.cleaned_data["action"]
  1405. select_across = action_form.cleaned_data["select_across"]
  1406. func = self.get_actions(request)[action][0]
  1407. # Get the list of selected PKs. If nothing's selected, we can't
  1408. # perform an action on it, so bail. Except we want to perform
  1409. # the action explicitly on all objects.
  1410. selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
  1411. if not selected and not select_across:
  1412. # Reminder that something needs to be selected or nothing will happen
  1413. msg = _(
  1414. "Items must be selected in order to perform "
  1415. "actions on them. No items have been changed."
  1416. )
  1417. self.message_user(request, msg, messages.WARNING)
  1418. return None
  1419. if not select_across:
  1420. # Perform the action only on the selected objects
  1421. queryset = queryset.filter(pk__in=selected)
  1422. response = func(self, request, queryset)
  1423. # Actions may return an HttpResponse-like object, which will be
  1424. # used as the response from the POST. If not, we'll be a good
  1425. # little HTTP citizen and redirect back to the changelist page.
  1426. if isinstance(response, HttpResponseBase):
  1427. return response
  1428. else:
  1429. return HttpResponseRedirect(request.get_full_path())
  1430. else:
  1431. msg = _("No action selected.")
  1432. self.message_user(request, msg, messages.WARNING)
  1433. return None
  1434. def response_delete(self, request, obj_display, obj_id):
  1435. """
  1436. Determine the HttpResponse for the delete_view stage.
  1437. """
  1438. opts = self.model._meta
  1439. if IS_POPUP_VAR in request.POST:
  1440. popup_response_data = json.dumps(
  1441. {
  1442. "action": "delete",
  1443. "value": str(obj_id),
  1444. }
  1445. )
  1446. return TemplateResponse(
  1447. request,
  1448. self.popup_response_template
  1449. or [
  1450. "admin/%s/%s/popup_response.html"
  1451. % (opts.app_label, opts.model_name),
  1452. "admin/%s/popup_response.html" % opts.app_label,
  1453. "admin/popup_response.html",
  1454. ],
  1455. {
  1456. "popup_response_data": popup_response_data,
  1457. },
  1458. )
  1459. self.message_user(
  1460. request,
  1461. _("The %(name)s “%(obj)s” was deleted successfully.")
  1462. % {
  1463. "name": opts.verbose_name,
  1464. "obj": obj_display,
  1465. },
  1466. messages.SUCCESS,
  1467. )
  1468. if self.has_change_permission(request, None):
  1469. post_url = reverse(
  1470. "admin:%s_%s_changelist" % (opts.app_label, opts.model_name),
  1471. current_app=self.admin_site.name,
  1472. )
  1473. preserved_filters = self.get_preserved_filters(request)
  1474. post_url = add_preserved_filters(
  1475. {"preserved_filters": preserved_filters, "opts": opts}, post_url
  1476. )
  1477. else:
  1478. post_url = reverse("admin:index", current_app=self.admin_site.name)
  1479. return HttpResponseRedirect(post_url)
  1480. def render_delete_form(self, request, context):
  1481. opts = self.model._meta
  1482. app_label = opts.app_label
  1483. request.current_app = self.admin_site.name
  1484. context.update(
  1485. to_field_var=TO_FIELD_VAR,
  1486. is_popup_var=IS_POPUP_VAR,
  1487. media=self.media,
  1488. )
  1489. return TemplateResponse(
  1490. request,
  1491. self.delete_confirmation_template
  1492. or [
  1493. "admin/{}/{}/delete_confirmation.html".format(
  1494. app_label, opts.model_name
  1495. ),
  1496. "admin/{}/delete_confirmation.html".format(app_label),
  1497. "admin/delete_confirmation.html",
  1498. ],
  1499. context,
  1500. )
  1501. def get_inline_formsets(self, request, formsets, inline_instances, obj=None):
  1502. # Edit permissions on parent model are required for editable inlines.
  1503. can_edit_parent = (
  1504. self.has_change_permission(request, obj)
  1505. if obj
  1506. else self.has_add_permission(request)
  1507. )
  1508. inline_admin_formsets = []
  1509. for inline, formset in zip(inline_instances, formsets):
  1510. fieldsets = list(inline.get_fieldsets(request, obj))
  1511. readonly = list(inline.get_readonly_fields(request, obj))
  1512. if can_edit_parent:
  1513. has_add_permission = inline.has_add_permission(request, obj)
  1514. has_change_permission = inline.has_change_permission(request, obj)
  1515. has_delete_permission = inline.has_delete_permission(request, obj)
  1516. else:
  1517. # Disable all edit-permissions, and overide formset settings.
  1518. has_add_permission = (
  1519. has_change_permission
  1520. ) = has_delete_permission = False
  1521. formset.extra = formset.max_num = 0
  1522. has_view_permission = inline.has_view_permission(request, obj)
  1523. prepopulated = dict(inline.get_prepopulated_fields(request, obj))
  1524. inline_admin_formset = helpers.InlineAdminFormSet(
  1525. inline,
  1526. formset,
  1527. fieldsets,
  1528. prepopulated,
  1529. readonly,
  1530. model_admin=self,
  1531. has_add_permission=has_add_permission,
  1532. has_change_permission=has_change_permission,
  1533. has_delete_permission=has_delete_permission,
  1534. has_view_permission=has_view_permission,
  1535. )
  1536. inline_admin_formsets.append(inline_admin_formset)
  1537. return inline_admin_formsets
  1538. def get_changeform_initial_data(self, request):
  1539. """
  1540. Get the initial form data from the request's GET params.
  1541. """
  1542. initial = dict(request.GET.items())
  1543. for k in initial:
  1544. try:
  1545. f = self.model._meta.get_field(k)
  1546. except FieldDoesNotExist:
  1547. continue
  1548. # We have to special-case M2Ms as a list of comma-separated PKs.
  1549. if isinstance(f, models.ManyToManyField):
  1550. initial[k] = initial[k].split(",")
  1551. return initial
  1552. def _get_obj_does_not_exist_redirect(self, request, opts, object_id):
  1553. """
  1554. Create a message informing the user that the object doesn't exist
  1555. and return a redirect to the admin index page.
  1556. """
  1557. msg = _("%(name)s with ID “%(key)s” doesn’t exist. Perhaps it was deleted?") % {
  1558. "name": opts.verbose_name,
  1559. "key": unquote(object_id),
  1560. }
  1561. self.message_user(request, msg, messages.WARNING)
  1562. url = reverse("admin:index", current_app=self.admin_site.name)
  1563. return HttpResponseRedirect(url)
  1564. @csrf_protect_m
  1565. def changeform_view(self, request, object_id=None, form_url="", extra_context=None):
  1566. with transaction.atomic(using=router.db_for_write(self.model)):
  1567. return self._changeform_view(request, object_id, form_url, extra_context)
  1568. def _changeform_view(self, request, object_id, form_url, extra_context):
  1569. to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))
  1570. if to_field and not self.to_field_allowed(request, to_field):
  1571. raise DisallowedModelAdminToField(
  1572. "The field %s cannot be referenced." % to_field
  1573. )
  1574. model = self.model
  1575. opts = model._meta
  1576. if request.method == "POST" and "_saveasnew" in request.POST:
  1577. object_id = None
  1578. add = object_id is None
  1579. if add:
  1580. if not self.has_add_permission(request):
  1581. raise PermissionDenied
  1582. obj = None
  1583. else:
  1584. obj = self.get_object(request, unquote(object_id), to_field)
  1585. if request.method == "POST":
  1586. if not self.has_change_permission(request, obj):
  1587. raise PermissionDenied
  1588. else:
  1589. if not self.has_view_or_change_permission(request, obj):
  1590. raise PermissionDenied
  1591. if obj is None:
  1592. return self._get_obj_does_not_exist_redirect(request, opts, object_id)
  1593. fieldsets = self.get_fieldsets(request, obj)
  1594. ModelForm = self.get_form(
  1595. request, obj, change=not add, fields=flatten_fieldsets(fieldsets)
  1596. )
  1597. if request.method == "POST":
  1598. form = ModelForm(request.POST, request.FILES, instance=obj)
  1599. formsets, inline_instances = self._create_formsets(
  1600. request,
  1601. form.instance,
  1602. change=not add,
  1603. )
  1604. form_validated = form.is_valid()
  1605. if form_validated:
  1606. new_object = self.save_form(request, form, change=not add)
  1607. else:
  1608. new_object = form.instance
  1609. if all_valid(formsets) and form_validated:
  1610. self.save_model(request, new_object, form, not add)
  1611. self.save_related(request, form, formsets, not add)
  1612. change_message = self.construct_change_message(
  1613. request, form, formsets, add
  1614. )
  1615. if add:
  1616. self.log_addition(request, new_object, change_message)
  1617. return self.response_add(request, new_object)
  1618. else:
  1619. self.log_change(request, new_object, change_message)
  1620. return self.response_change(request, new_object)
  1621. else:
  1622. form_validated = False
  1623. else:
  1624. if add:
  1625. initial = self.get_changeform_initial_data(request)
  1626. form = ModelForm(initial=initial)
  1627. formsets, inline_instances = self._create_formsets(
  1628. request, form.instance, change=False
  1629. )
  1630. else:
  1631. form = ModelForm(instance=obj)
  1632. formsets, inline_instances = self._create_formsets(
  1633. request, obj, change=True
  1634. )
  1635. if not add and not self.has_change_permission(request, obj):
  1636. readonly_fields = flatten_fieldsets(fieldsets)
  1637. else:
  1638. readonly_fields = self.get_readonly_fields(request, obj)
  1639. adminForm = helpers.AdminForm(
  1640. form,
  1641. list(fieldsets),
  1642. # Clear prepopulated fields on a view-only form to avoid a crash.
  1643. self.get_prepopulated_fields(request, obj)
  1644. if add or self.has_change_permission(request, obj)
  1645. else {},
  1646. readonly_fields,
  1647. model_admin=self,
  1648. )
  1649. media = self.media + adminForm.media
  1650. inline_formsets = self.get_inline_formsets(
  1651. request, formsets, inline_instances, obj
  1652. )
  1653. for inline_formset in inline_formsets:
  1654. media = media + inline_formset.media
  1655. if add:
  1656. title = _("Add %s")
  1657. elif self.has_change_permission(request, obj):
  1658. title = _("Change %s")
  1659. else:
  1660. title = _("View %s")
  1661. context = {
  1662. **self.admin_site.each_context(request),
  1663. "title": title % opts.verbose_name,
  1664. "subtitle": str(obj) if obj else None,
  1665. "adminform": adminForm,
  1666. "object_id": object_id,
  1667. "original": obj,
  1668. "is_popup": IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET,
  1669. "to_field": to_field,
  1670. "media": media,
  1671. "inline_admin_formsets": inline_formsets,
  1672. "errors": helpers.AdminErrorList(form, formsets),
  1673. "preserved_filters": self.get_preserved_filters(request),
  1674. }
  1675. # Hide the "Save" and "Save and continue" buttons if "Save as New" was
  1676. # previously chosen to prevent the interface from getting confusing.
  1677. if (
  1678. request.method == "POST"
  1679. and not form_validated
  1680. and "_saveasnew" in request.POST
  1681. ):
  1682. context["show_save"] = False
  1683. context["show_save_and_continue"] = False
  1684. # Use the change template instead of the add template.
  1685. add = False
  1686. context.update(extra_context or {})
  1687. return self.render_change_form(
  1688. request, context, add=add, change=not add, obj=obj, form_url=form_url
  1689. )
  1690. def add_view(self, request, form_url="", extra_context=None):
  1691. return self.changeform_view(request, None, form_url, extra_context)
  1692. def change_view(self, request, object_id, form_url="", extra_context=None):
  1693. return self.changeform_view(request, object_id, form_url, extra_context)
  1694. def _get_edited_object_pks(self, request, prefix):
  1695. """Return POST data values of list_editable primary keys."""
  1696. pk_pattern = re.compile(
  1697. r"{}-\d+-{}$".format(re.escape(prefix), self.model._meta.pk.name)
  1698. )
  1699. return [value for key, value in request.POST.items() if pk_pattern.match(key)]
  1700. def _get_list_editable_queryset(self, request, prefix):
  1701. """
  1702. Based on POST data, return a queryset of the objects that were edited
  1703. via list_editable.
  1704. """
  1705. object_pks = self._get_edited_object_pks(request, prefix)
  1706. queryset = self.get_queryset(request)
  1707. validate = queryset.model._meta.pk.to_python
  1708. try:
  1709. for pk in object_pks:
  1710. validate(pk)
  1711. except ValidationError:
  1712. # Disable the optimization if the POST data was tampered with.
  1713. return queryset
  1714. return queryset.filter(pk__in=object_pks)
  1715. @csrf_protect_m
  1716. def changelist_view(self, request, extra_context=None):
  1717. """
  1718. The 'change list' admin view for this model.
  1719. """
  1720. from django.contrib.admin.views.main import ERROR_FLAG
  1721. opts = self.model._meta
  1722. app_label = opts.app_label
  1723. if not self.has_view_or_change_permission(request):
  1724. raise PermissionDenied
  1725. try:
  1726. cl = self.get_changelist_instance(request)
  1727. except IncorrectLookupParameters:
  1728. # Wacky lookup parameters were given, so redirect to the main
  1729. # changelist page, without parameters, and pass an 'invalid=1'
  1730. # parameter via the query string. If wacky parameters were given
  1731. # and the 'invalid=1' parameter was already in the query string,
  1732. # something is screwed up with the database, so display an error
  1733. # page.
  1734. if ERROR_FLAG in request.GET:
  1735. return SimpleTemplateResponse(
  1736. "admin/invalid_setup.html",
  1737. {
  1738. "title": _("Database error"),
  1739. },
  1740. )
  1741. return HttpResponseRedirect(request.path + "?" + ERROR_FLAG + "=1")
  1742. # If the request was POSTed, this might be a bulk action or a bulk
  1743. # edit. Try to look up an action or confirmation first, but if this
  1744. # isn't an action the POST will fall through to the bulk edit check,
  1745. # below.
  1746. action_failed = False
  1747. selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
  1748. actions = self.get_actions(request)
  1749. # Actions with no confirmation
  1750. if (
  1751. actions
  1752. and request.method == "POST"
  1753. and "index" in request.POST
  1754. and "_save" not in request.POST
  1755. ):
  1756. if selected:
  1757. response = self.response_action(
  1758. request, queryset=cl.get_queryset(request)
  1759. )
  1760. if response:
  1761. return response
  1762. else:
  1763. action_failed = True
  1764. else:
  1765. msg = _(
  1766. "Items must be selected in order to perform "
  1767. "actions on them. No items have been changed."
  1768. )
  1769. self.message_user(request, msg, messages.WARNING)
  1770. action_failed = True
  1771. # Actions with confirmation
  1772. if (
  1773. actions
  1774. and request.method == "POST"
  1775. and helpers.ACTION_CHECKBOX_NAME in request.POST
  1776. and "index" not in request.POST
  1777. and "_save" not in request.POST
  1778. ):
  1779. if selected:
  1780. response = self.response_action(
  1781. request, queryset=cl.get_queryset(request)
  1782. )
  1783. if response:
  1784. return response
  1785. else:
  1786. action_failed = True
  1787. if action_failed:
  1788. # Redirect back to the changelist page to avoid resubmitting the
  1789. # form if the user refreshes the browser or uses the "No, take
  1790. # me back" button on the action confirmation page.
  1791. return HttpResponseRedirect(request.get_full_path())
  1792. # If we're allowing changelist editing, we need to construct a formset
  1793. # for the changelist given all the fields to be edited. Then we'll
  1794. # use the formset to validate/process POSTed data.
  1795. formset = cl.formset = None
  1796. # Handle POSTed bulk-edit data.
  1797. if request.method == "POST" and cl.list_editable and "_save" in request.POST:
  1798. if not self.has_change_permission(request):
  1799. raise PermissionDenied
  1800. FormSet = self.get_changelist_formset(request)
  1801. modified_objects = self._get_list_editable_queryset(
  1802. request, FormSet.get_default_prefix()
  1803. )
  1804. formset = cl.formset = FormSet(
  1805. request.POST, request.FILES, queryset=modified_objects
  1806. )
  1807. if formset.is_valid():
  1808. changecount = 0
  1809. for form in formset.forms:
  1810. if form.has_changed():
  1811. obj = self.save_form(request, form, change=True)
  1812. self.save_model(request, obj, form, change=True)
  1813. self.save_related(request, form, formsets=[], change=True)
  1814. change_msg = self.construct_change_message(request, form, None)
  1815. self.log_change(request, obj, change_msg)
  1816. changecount += 1
  1817. if changecount:
  1818. msg = ngettext(
  1819. "%(count)s %(name)s was changed successfully.",
  1820. "%(count)s %(name)s were changed successfully.",
  1821. changecount,
  1822. ) % {
  1823. "count": changecount,
  1824. "name": model_ngettext(opts, changecount),
  1825. }
  1826. self.message_user(request, msg, messages.SUCCESS)
  1827. return HttpResponseRedirect(request.get_full_path())
  1828. # Handle GET -- construct a formset for display.
  1829. elif cl.list_editable and self.has_change_permission(request):
  1830. FormSet = self.get_changelist_formset(request)
  1831. formset = cl.formset = FormSet(queryset=cl.result_list)
  1832. # Build the list of media to be used by the formset.
  1833. if formset:
  1834. media = self.media + formset.media
  1835. else:
  1836. media = self.media
  1837. # Build the action form and populate it with available actions.
  1838. if actions:
  1839. action_form = self.action_form(auto_id=None)
  1840. action_form.fields["action"].choices = self.get_action_choices(request)
  1841. media += action_form.media
  1842. else:
  1843. action_form = None
  1844. selection_note_all = ngettext(
  1845. "%(total_count)s selected", "All %(total_count)s selected", cl.result_count
  1846. )
  1847. context = {
  1848. **self.admin_site.each_context(request),
  1849. "module_name": str(opts.verbose_name_plural),
  1850. "selection_note": _("0 of %(cnt)s selected") % {"cnt": len(cl.result_list)},
  1851. "selection_note_all": selection_note_all % {"total_count": cl.result_count},
  1852. "title": cl.title,
  1853. "subtitle": None,
  1854. "is_popup": cl.is_popup,
  1855. "to_field": cl.to_field,
  1856. "cl": cl,
  1857. "media": media,
  1858. "has_add_permission": self.has_add_permission(request),
  1859. "opts": cl.opts,
  1860. "action_form": action_form,
  1861. "actions_on_top": self.actions_on_top,
  1862. "actions_on_bottom": self.actions_on_bottom,
  1863. "actions_selection_counter": self.actions_selection_counter,
  1864. "preserved_filters": self.get_preserved_filters(request),
  1865. **(extra_context or {}),
  1866. }
  1867. request.current_app = self.admin_site.name
  1868. return TemplateResponse(
  1869. request,
  1870. self.change_list_template
  1871. or [
  1872. "admin/%s/%s/change_list.html" % (app_label, opts.model_name),
  1873. "admin/%s/change_list.html" % app_label,
  1874. "admin/change_list.html",
  1875. ],
  1876. context,
  1877. )
  1878. def get_deleted_objects(self, objs, request):
  1879. """
  1880. Hook for customizing the delete process for the delete view and the
  1881. "delete selected" action.
  1882. """
  1883. return get_deleted_objects(objs, request, self.admin_site)
  1884. @csrf_protect_m
  1885. def delete_view(self, request, object_id, extra_context=None):
  1886. with transaction.atomic(using=router.db_for_write(self.model)):
  1887. return self._delete_view(request, object_id, extra_context)
  1888. def _delete_view(self, request, object_id, extra_context):
  1889. "The 'delete' admin view for this model."
  1890. opts = self.model._meta
  1891. app_label = opts.app_label
  1892. to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))
  1893. if to_field and not self.to_field_allowed(request, to_field):
  1894. raise DisallowedModelAdminToField(
  1895. "The field %s cannot be referenced." % to_field
  1896. )
  1897. obj = self.get_object(request, unquote(object_id), to_field)
  1898. if not self.has_delete_permission(request, obj):
  1899. raise PermissionDenied
  1900. if obj is None:
  1901. return self._get_obj_does_not_exist_redirect(request, opts, object_id)
  1902. # Populate deleted_objects, a data structure of all related objects that
  1903. # will also be deleted.
  1904. (
  1905. deleted_objects,
  1906. model_count,
  1907. perms_needed,
  1908. protected,
  1909. ) = self.get_deleted_objects([obj], request)
  1910. if request.POST and not protected: # The user has confirmed the deletion.
  1911. if perms_needed:
  1912. raise PermissionDenied
  1913. obj_display = str(obj)
  1914. attr = str(to_field) if to_field else opts.pk.attname
  1915. obj_id = obj.serializable_value(attr)
  1916. self.log_deletion(request, obj, obj_display)
  1917. self.delete_model(request, obj)
  1918. return self.response_delete(request, obj_display, obj_id)
  1919. object_name = str(opts.verbose_name)
  1920. if perms_needed or protected:
  1921. title = _("Cannot delete %(name)s") % {"name": object_name}
  1922. else:
  1923. title = _("Are you sure?")
  1924. context = {
  1925. **self.admin_site.each_context(request),
  1926. "title": title,
  1927. "subtitle": None,
  1928. "object_name": object_name,
  1929. "object": obj,
  1930. "deleted_objects": deleted_objects,
  1931. "model_count": dict(model_count).items(),
  1932. "perms_lacking": perms_needed,
  1933. "protected": protected,
  1934. "opts": opts,
  1935. "app_label": app_label,
  1936. "preserved_filters": self.get_preserved_filters(request),
  1937. "is_popup": IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET,
  1938. "to_field": to_field,
  1939. **(extra_context or {}),
  1940. }
  1941. return self.render_delete_form(request, context)
  1942. def history_view(self, request, object_id, extra_context=None):
  1943. "The 'history' admin view for this model."
  1944. from django.contrib.admin.models import LogEntry
  1945. from django.contrib.admin.views.main import PAGE_VAR
  1946. # First check if the user can see this history.
  1947. model = self.model
  1948. obj = self.get_object(request, unquote(object_id))
  1949. if obj is None:
  1950. return self._get_obj_does_not_exist_redirect(
  1951. request, model._meta, object_id
  1952. )
  1953. if not self.has_view_or_change_permission(request, obj):
  1954. raise PermissionDenied
  1955. # Then get the history for this object.
  1956. opts = model._meta
  1957. app_label = opts.app_label
  1958. action_list = (
  1959. LogEntry.objects.filter(
  1960. object_id=unquote(object_id),
  1961. content_type=get_content_type_for_model(model),
  1962. )
  1963. .select_related()
  1964. .order_by("action_time")
  1965. )
  1966. paginator = self.get_paginator(request, action_list, 100)
  1967. page_number = request.GET.get(PAGE_VAR, 1)
  1968. page_obj = paginator.get_page(page_number)
  1969. page_range = paginator.get_elided_page_range(page_obj.number)
  1970. context = {
  1971. **self.admin_site.each_context(request),
  1972. "title": _("Change history: %s") % obj,
  1973. "subtitle": None,
  1974. "action_list": page_obj,
  1975. "page_range": page_range,
  1976. "page_var": PAGE_VAR,
  1977. "pagination_required": paginator.count > 100,
  1978. "module_name": str(capfirst(opts.verbose_name_plural)),
  1979. "object": obj,
  1980. "opts": opts,
  1981. "preserved_filters": self.get_preserved_filters(request),
  1982. **(extra_context or {}),
  1983. }
  1984. request.current_app = self.admin_site.name
  1985. return TemplateResponse(
  1986. request,
  1987. self.object_history_template
  1988. or [
  1989. "admin/%s/%s/object_history.html" % (app_label, opts.model_name),
  1990. "admin/%s/object_history.html" % app_label,
  1991. "admin/object_history.html",
  1992. ],
  1993. context,
  1994. )
  1995. def get_formset_kwargs(self, request, obj, inline, prefix):
  1996. formset_params = {
  1997. "instance": obj,
  1998. "prefix": prefix,
  1999. "queryset": inline.get_queryset(request),
  2000. }
  2001. if request.method == "POST":
  2002. formset_params.update(
  2003. {
  2004. "data": request.POST.copy(),
  2005. "files": request.FILES,
  2006. "save_as_new": "_saveasnew" in request.POST,
  2007. }
  2008. )
  2009. return formset_params
  2010. def _create_formsets(self, request, obj, change):
  2011. "Helper function to generate formsets for add/change_view."
  2012. formsets = []
  2013. inline_instances = []
  2014. prefixes = {}
  2015. get_formsets_args = [request]
  2016. if change:
  2017. get_formsets_args.append(obj)
  2018. for FormSet, inline in self.get_formsets_with_inlines(*get_formsets_args):
  2019. prefix = FormSet.get_default_prefix()
  2020. prefixes[prefix] = prefixes.get(prefix, 0) + 1
  2021. if prefixes[prefix] != 1 or not prefix:
  2022. prefix = "%s-%s" % (prefix, prefixes[prefix])
  2023. formset_params = self.get_formset_kwargs(request, obj, inline, prefix)
  2024. formset = FormSet(**formset_params)
  2025. def user_deleted_form(request, obj, formset, index):
  2026. """Return whether or not the user deleted the form."""
  2027. return (
  2028. inline.has_delete_permission(request, obj)
  2029. and "{}-{}-DELETE".format(formset.prefix, index) in request.POST
  2030. )
  2031. # Bypass validation of each view-only inline form (since the form's
  2032. # data won't be in request.POST), unless the form was deleted.
  2033. if not inline.has_change_permission(request, obj if change else None):
  2034. for index, form in enumerate(formset.initial_forms):
  2035. if user_deleted_form(request, obj, formset, index):
  2036. continue
  2037. form._errors = {}
  2038. form.cleaned_data = form.initial
  2039. formsets.append(formset)
  2040. inline_instances.append(inline)
  2041. return formsets, inline_instances
  2042. class InlineModelAdmin(BaseModelAdmin):
  2043. """
  2044. Options for inline editing of ``model`` instances.
  2045. Provide ``fk_name`` to specify the attribute name of the ``ForeignKey``
  2046. from ``model`` to its parent. This is required if ``model`` has more than
  2047. one ``ForeignKey`` to its parent.
  2048. """
  2049. model = None
  2050. fk_name = None
  2051. formset = BaseInlineFormSet
  2052. extra = 3
  2053. min_num = None
  2054. max_num = None
  2055. template = None
  2056. verbose_name = None
  2057. verbose_name_plural = None
  2058. can_delete = True
  2059. show_change_link = False
  2060. checks_class = InlineModelAdminChecks
  2061. classes = None
  2062. def __init__(self, parent_model, admin_site):
  2063. self.admin_site = admin_site
  2064. self.parent_model = parent_model
  2065. self.opts = self.model._meta
  2066. self.has_registered_model = admin_site.is_registered(self.model)
  2067. super().__init__()
  2068. if self.verbose_name_plural is None:
  2069. if self.verbose_name is None:
  2070. self.verbose_name_plural = self.model._meta.verbose_name_plural
  2071. else:
  2072. self.verbose_name_plural = format_lazy("{}s", self.verbose_name)
  2073. if self.verbose_name is None:
  2074. self.verbose_name = self.model._meta.verbose_name
  2075. @property
  2076. def media(self):
  2077. extra = "" if settings.DEBUG else ".min"
  2078. js = ["vendor/jquery/jquery%s.js" % extra, "jquery.init.js", "inlines.js"]
  2079. if self.filter_vertical or self.filter_horizontal:
  2080. js.extend(["SelectBox.js", "SelectFilter2.js"])
  2081. if self.classes and "collapse" in self.classes:
  2082. js.append("collapse.js")
  2083. return forms.Media(js=["admin/js/%s" % url for url in js])
  2084. def get_extra(self, request, obj=None, **kwargs):
  2085. """Hook for customizing the number of extra inline forms."""
  2086. return self.extra
  2087. def get_min_num(self, request, obj=None, **kwargs):
  2088. """Hook for customizing the min number of inline forms."""
  2089. return self.min_num
  2090. def get_max_num(self, request, obj=None, **kwargs):
  2091. """Hook for customizing the max number of extra inline forms."""
  2092. return self.max_num
  2093. def get_formset(self, request, obj=None, **kwargs):
  2094. """Return a BaseInlineFormSet class for use in admin add/change views."""
  2095. if "fields" in kwargs:
  2096. fields = kwargs.pop("fields")
  2097. else:
  2098. fields = flatten_fieldsets(self.get_fieldsets(request, obj))
  2099. excluded = self.get_exclude(request, obj)
  2100. exclude = [] if excluded is None else list(excluded)
  2101. exclude.extend(self.get_readonly_fields(request, obj))
  2102. if excluded is None and hasattr(self.form, "_meta") and self.form._meta.exclude:
  2103. # Take the custom ModelForm's Meta.exclude into account only if the
  2104. # InlineModelAdmin doesn't define its own.
  2105. exclude.extend(self.form._meta.exclude)
  2106. # If exclude is an empty list we use None, since that's the actual
  2107. # default.
  2108. exclude = exclude or None
  2109. can_delete = self.can_delete and self.has_delete_permission(request, obj)
  2110. defaults = {
  2111. "form": self.form,
  2112. "formset": self.formset,
  2113. "fk_name": self.fk_name,
  2114. "fields": fields,
  2115. "exclude": exclude,
  2116. "formfield_callback": partial(self.formfield_for_dbfield, request=request),
  2117. "extra": self.get_extra(request, obj, **kwargs),
  2118. "min_num": self.get_min_num(request, obj, **kwargs),
  2119. "max_num": self.get_max_num(request, obj, **kwargs),
  2120. "can_delete": can_delete,
  2121. **kwargs,
  2122. }
  2123. base_model_form = defaults["form"]
  2124. can_change = self.has_change_permission(request, obj) if request else True
  2125. can_add = self.has_add_permission(request, obj) if request else True
  2126. class DeleteProtectedModelForm(base_model_form):
  2127. def hand_clean_DELETE(self):
  2128. """
  2129. We don't validate the 'DELETE' field itself because on
  2130. templates it's not rendered using the field information, but
  2131. just using a generic "deletion_field" of the InlineModelAdmin.
  2132. """
  2133. if self.cleaned_data.get(DELETION_FIELD_NAME, False):
  2134. using = router.db_for_write(self._meta.model)
  2135. collector = NestedObjects(using=using)
  2136. if self.instance._state.adding:
  2137. return
  2138. collector.collect([self.instance])
  2139. if collector.protected:
  2140. objs = []
  2141. for p in collector.protected:
  2142. objs.append(
  2143. # Translators: Model verbose name and instance
  2144. # representation, suitable to be an item in a
  2145. # list.
  2146. _("%(class_name)s %(instance)s")
  2147. % {"class_name": p._meta.verbose_name, "instance": p}
  2148. )
  2149. params = {
  2150. "class_name": self._meta.model._meta.verbose_name,
  2151. "instance": self.instance,
  2152. "related_objects": get_text_list(objs, _("and")),
  2153. }
  2154. msg = _(
  2155. "Deleting %(class_name)s %(instance)s would require "
  2156. "deleting the following protected related objects: "
  2157. "%(related_objects)s"
  2158. )
  2159. raise ValidationError(
  2160. msg, code="deleting_protected", params=params
  2161. )
  2162. def is_valid(self):
  2163. result = super().is_valid()
  2164. self.hand_clean_DELETE()
  2165. return result
  2166. def has_changed(self):
  2167. # Protect against unauthorized edits.
  2168. if not can_change and not self.instance._state.adding:
  2169. return False
  2170. if not can_add and self.instance._state.adding:
  2171. return False
  2172. return super().has_changed()
  2173. defaults["form"] = DeleteProtectedModelForm
  2174. if defaults["fields"] is None and not modelform_defines_fields(
  2175. defaults["form"]
  2176. ):
  2177. defaults["fields"] = forms.ALL_FIELDS
  2178. return inlineformset_factory(self.parent_model, self.model, **defaults)
  2179. def _get_form_for_get_fields(self, request, obj=None):
  2180. return self.get_formset(request, obj, fields=None).form
  2181. def get_queryset(self, request):
  2182. queryset = super().get_queryset(request)
  2183. if not self.has_view_or_change_permission(request):
  2184. queryset = queryset.none()
  2185. return queryset
  2186. def _has_any_perms_for_target_model(self, request, perms):
  2187. """
  2188. This method is called only when the ModelAdmin's model is for an
  2189. ManyToManyField's implicit through model (if self.opts.auto_created).
  2190. Return True if the user has any of the given permissions ('add',
  2191. 'change', etc.) for the model that points to the through model.
  2192. """
  2193. opts = self.opts
  2194. # Find the target model of an auto-created many-to-many relationship.
  2195. for field in opts.fields:
  2196. if field.remote_field and field.remote_field.model != self.parent_model:
  2197. opts = field.remote_field.model._meta
  2198. break
  2199. return any(
  2200. request.user.has_perm(
  2201. "%s.%s" % (opts.app_label, get_permission_codename(perm, opts))
  2202. )
  2203. for perm in perms
  2204. )
  2205. def has_add_permission(self, request, obj):
  2206. if self.opts.auto_created:
  2207. # Auto-created intermediate models don't have their own
  2208. # permissions. The user needs to have the change permission for the
  2209. # related model in order to be able to do anything with the
  2210. # intermediate model.
  2211. return self._has_any_perms_for_target_model(request, ["change"])
  2212. return super().has_add_permission(request)
  2213. def has_change_permission(self, request, obj=None):
  2214. if self.opts.auto_created:
  2215. # Same comment as has_add_permission().
  2216. return self._has_any_perms_for_target_model(request, ["change"])
  2217. return super().has_change_permission(request)
  2218. def has_delete_permission(self, request, obj=None):
  2219. if self.opts.auto_created:
  2220. # Same comment as has_add_permission().
  2221. return self._has_any_perms_for_target_model(request, ["change"])
  2222. return super().has_delete_permission(request, obj)
  2223. def has_view_permission(self, request, obj=None):
  2224. if self.opts.auto_created:
  2225. # Same comment as has_add_permission(). The 'change' permission
  2226. # also implies the 'view' permission.
  2227. return self._has_any_perms_for_target_model(request, ["view", "change"])
  2228. return super().has_view_permission(request)
  2229. class StackedInline(InlineModelAdmin):
  2230. template = "admin/edit_inline/stacked.html"
  2231. class TabularInline(InlineModelAdmin):
  2232. template = "admin/edit_inline/tabular.html"