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 90KB

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