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.
 
 
 
 

1919 lines
79 KiB

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