2015-09-07 17:51:03 +08:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2012-12-08 19:41:11 +08:00
|
|
|
import copy
|
2015-11-23 18:46:19 +08:00
|
|
|
import json
|
2013-05-19 16:52:29 +08:00
|
|
|
import operator
|
2015-01-28 20:35:27 +08:00
|
|
|
from collections import OrderedDict
|
2013-05-19 23:58:29 +08:00
|
|
|
from functools import partial, reduce, update_wrapper
|
2012-10-19 07:58:52 +08:00
|
|
|
|
2011-04-23 02:17:16 +08:00
|
|
|
from django import forms
|
2012-02-05 16:35:08 +08:00
|
|
|
from django.conf import settings
|
2013-06-23 09:48:09 +08:00
|
|
|
from django.contrib import messages
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.contrib.admin import helpers, widgets
|
|
|
|
from django.contrib.admin.checks import (
|
|
|
|
BaseModelAdminChecks, InlineModelAdminChecks, ModelAdminChecks,
|
|
|
|
)
|
2014-08-07 12:18:10 +08:00
|
|
|
from django.contrib.admin.exceptions import DisallowedModelAdminToField
|
2013-06-19 03:41:36 +08:00
|
|
|
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.contrib.admin.utils import (
|
|
|
|
NestedObjects, flatten_fieldsets, get_deleted_objects,
|
|
|
|
lookup_needs_distinct, model_format_dict, quote, unquote,
|
|
|
|
)
|
2013-06-23 09:48:09 +08:00
|
|
|
from django.contrib.auth import get_permission_codename
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.core.exceptions import (
|
|
|
|
FieldDoesNotExist, FieldError, PermissionDenied, ValidationError,
|
|
|
|
)
|
2010-12-21 22:57:29 +08:00
|
|
|
from django.core.paginator import Paginator
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.db import models, router, transaction
|
2012-09-09 07:51:36 +08:00
|
|
|
from django.db.models.constants import LOOKUP_SEP
|
2015-01-02 23:14:23 +08:00
|
|
|
from django.db.models.fields import BLANK_CHOICE_DASH
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.forms.formsets import DELETION_FIELD_NAME, all_valid
|
|
|
|
from django.forms.models import (
|
|
|
|
BaseInlineFormSet, inlineformset_factory, modelform_defines_fields,
|
|
|
|
modelform_factory, modelformset_factory,
|
|
|
|
)
|
|
|
|
from django.forms.widgets import CheckboxSelectMultiple, SelectMultiple
|
2013-02-26 11:27:52 +08:00
|
|
|
from django.http import Http404, HttpResponseRedirect
|
2013-05-29 22:55:56 +08:00
|
|
|
from django.http.response import HttpResponseBase
|
2011-04-23 02:17:16 +08:00
|
|
|
from django.template.response import SimpleTemplateResponse, TemplateResponse
|
2015-12-30 23:51:16 +08:00
|
|
|
from django.urls import reverse
|
2012-07-21 03:20:42 +08:00
|
|
|
from django.utils import six
|
2014-01-20 10:45:21 +08:00
|
|
|
from django.utils.decorators import method_decorator
|
2014-02-27 05:48:20 +08:00
|
|
|
from django.utils.encoding import force_text, python_2_unicode_compatible
|
2015-11-23 18:46:19 +08:00
|
|
|
from django.utils.html import escape, format_html
|
2015-09-07 17:51:03 +08:00
|
|
|
from django.utils.http import urlencode, urlquote
|
2014-01-20 10:45:21 +08:00
|
|
|
from django.utils.safestring import mark_safe
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils.text import capfirst, get_text_list
|
2015-12-27 02:51:22 +08:00
|
|
|
from django.utils.translation import (
|
|
|
|
override as translation_override, string_concat, ugettext as _, ungettext,
|
|
|
|
)
|
2013-06-23 09:48:09 +08:00
|
|
|
from django.views.decorators.csrf import csrf_protect
|
2015-02-08 00:55:47 +08:00
|
|
|
from django.views.generic import RedirectView
|
2013-06-23 09:48:09 +08:00
|
|
|
|
2013-06-20 04:09:40 +08:00
|
|
|
IS_POPUP_VAR = '_popup'
|
2013-09-08 00:52:14 +08:00
|
|
|
TO_FIELD_VAR = '_to_field'
|
2013-06-20 04:09:40 +08:00
|
|
|
|
2013-12-26 20:46:15 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
HORIZONTAL, VERTICAL = 1, 2
|
2013-12-26 20:46:15 +08:00
|
|
|
|
|
|
|
|
2014-02-02 02:30:54 +08:00
|
|
|
def get_content_type_for_model(obj):
|
|
|
|
# Since this module gets imported in the application's root package,
|
|
|
|
# it cannot import models from other applications at the module level.
|
|
|
|
from django.contrib.contenttypes.models import ContentType
|
2014-04-07 21:04:49 +08:00
|
|
|
return ContentType.objects.get_for_model(obj, for_concrete_model=False)
|
2014-02-02 02:30:54 +08:00
|
|
|
|
|
|
|
|
2013-12-26 20:46:15 +08:00
|
|
|
def get_ul_class(radio_style):
|
|
|
|
return 'radiolist' if radio_style == VERTICAL else 'radiolist inline'
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2012-12-23 03:00:08 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
class IncorrectLookupParameters(Exception):
|
|
|
|
pass
|
|
|
|
|
2009-01-16 23:32:31 +08:00
|
|
|
# Defaults for formfield_overrides. ModelAdmin subclasses can change this
|
|
|
|
# by adding to ModelAdmin.formfield_overrides.
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-01-16 23:32:31 +08:00
|
|
|
FORMFIELD_FOR_DBFIELD_DEFAULTS = {
|
2009-03-18 17:19:24 +08:00
|
|
|
models.DateTimeField: {
|
2009-01-16 23:32:31 +08:00
|
|
|
'form_class': forms.SplitDateTimeField,
|
2009-03-18 17:19:24 +08:00
|
|
|
'widget': widgets.AdminSplitDateTime
|
2009-01-16 23:32:31 +08:00
|
|
|
},
|
2013-06-23 09:48:09 +08:00
|
|
|
models.DateField: {'widget': widgets.AdminDateWidget},
|
|
|
|
models.TimeField: {'widget': widgets.AdminTimeWidget},
|
|
|
|
models.TextField: {'widget': widgets.AdminTextareaWidget},
|
|
|
|
models.URLField: {'widget': widgets.AdminURLFieldWidget},
|
|
|
|
models.IntegerField: {'widget': widgets.AdminIntegerFieldWidget},
|
2012-06-05 19:28:32 +08:00
|
|
|
models.BigIntegerField: {'widget': widgets.AdminBigIntegerFieldWidget},
|
2013-06-23 09:48:09 +08:00
|
|
|
models.CharField: {'widget': widgets.AdminTextInputWidget},
|
|
|
|
models.ImageField: {'widget': widgets.AdminFileWidget},
|
|
|
|
models.FileField: {'widget': widgets.AdminFileWidget},
|
2013-07-26 19:22:30 +08:00
|
|
|
models.EmailField: {'widget': widgets.AdminEmailInputWidget},
|
2009-01-16 23:32:31 +08:00
|
|
|
}
|
|
|
|
|
2010-02-09 23:02:39 +08:00
|
|
|
csrf_protect_m = method_decorator(csrf_protect)
|
2009-01-16 23:32:31 +08:00
|
|
|
|
2012-12-23 03:00:08 +08:00
|
|
|
|
2014-03-21 19:45:38 +08:00
|
|
|
class BaseModelAdmin(six.with_metaclass(forms.MediaDefiningClass)):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""Functionality common to both ModelAdmin and InlineAdmin."""
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
raw_id_fields = ()
|
|
|
|
fields = None
|
2008-09-03 01:26:24 +08:00
|
|
|
exclude = None
|
2008-07-19 07:54:34 +08:00
|
|
|
fieldsets = None
|
|
|
|
form = forms.ModelForm
|
|
|
|
filter_vertical = ()
|
|
|
|
filter_horizontal = ()
|
|
|
|
radio_fields = {}
|
|
|
|
prepopulated_fields = {}
|
2009-01-16 23:32:31 +08:00
|
|
|
formfield_overrides = {}
|
2009-12-23 02:29:00 +08:00
|
|
|
readonly_fields = ()
|
2010-12-13 06:56:01 +08:00
|
|
|
ordering = None
|
2013-10-24 23:28:09 +08:00
|
|
|
view_on_site = True
|
2014-09-23 00:46:43 +08:00
|
|
|
show_full_result_count = True
|
2014-01-20 10:45:21 +08:00
|
|
|
checks_class = BaseModelAdminChecks
|
2013-02-23 23:10:32 +08:00
|
|
|
|
2015-09-10 21:05:31 +08:00
|
|
|
def check(self, **kwargs):
|
|
|
|
return self.checks_class().check(self, **kwargs)
|
2014-01-20 10:45:21 +08:00
|
|
|
|
2009-01-16 23:32:31 +08:00
|
|
|
def __init__(self):
|
2010-04-16 19:11:55 +08:00
|
|
|
overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy()
|
|
|
|
overrides.update(self.formfield_overrides)
|
|
|
|
self.formfield_overrides = overrides
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2015-12-24 23:25:59 +08:00
|
|
|
def formfield_for_dbfield(self, db_field, request, **kwargs):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
|
|
|
Hook for specifying the form Field instance for a given database Field
|
|
|
|
instance.
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
If kwargs are given, they're passed to the form Field's constructor.
|
|
|
|
"""
|
2008-07-30 19:41:04 +08:00
|
|
|
# If the field specifies choices, we don't need to look for special
|
|
|
|
# admin widgets - we just need to use a select widget of some kind.
|
|
|
|
if db_field.choices:
|
2009-01-16 23:32:31 +08:00
|
|
|
return self.formfield_for_choice_field(db_field, request, **kwargs)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2016-03-11 01:21:25 +08:00
|
|
|
# Foreign key or many-to-many fields
|
|
|
|
if db_field.many_to_many or isinstance(db_field, models.ForeignKey):
|
2009-01-16 23:32:31 +08:00
|
|
|
# Combine the field kwargs with any options for formfield_overrides.
|
2009-03-18 17:19:24 +08:00
|
|
|
# Make sure the passed in **kwargs override anything in
|
2009-01-16 23:32:31 +08:00
|
|
|
# formfield_overrides because **kwargs is more specific, and should
|
|
|
|
# always win.
|
|
|
|
if db_field.__class__ in self.formfield_overrides:
|
|
|
|
kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-01-16 23:32:31 +08:00
|
|
|
# Get the correct formfield.
|
|
|
|
if isinstance(db_field, models.ForeignKey):
|
|
|
|
formfield = self.formfield_for_foreignkey(db_field, request, **kwargs)
|
2016-03-11 01:21:25 +08:00
|
|
|
elif db_field.many_to_many:
|
2009-01-16 23:32:31 +08:00
|
|
|
formfield = self.formfield_for_manytomany(db_field, request, **kwargs)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-01-16 23:32:31 +08:00
|
|
|
# For non-raw_id fields, wrap the widget with a wrapper that adds
|
|
|
|
# extra HTML -- the "add other" interface -- to the end of the
|
2009-03-18 17:19:24 +08:00
|
|
|
# rendered output. formfield can be None if it came from a
|
2009-01-16 23:32:31 +08:00
|
|
|
# OneToOneField with parent_link=True or a M2M intermediary.
|
|
|
|
if formfield and db_field.name not in self.raw_id_fields:
|
2015-02-26 22:19:17 +08:00
|
|
|
related_modeladmin = self.admin_site._registry.get(db_field.remote_field.model)
|
2013-11-18 06:26:20 +08:00
|
|
|
wrapper_kwargs = {}
|
|
|
|
if related_modeladmin:
|
|
|
|
wrapper_kwargs.update(
|
|
|
|
can_add_related=related_modeladmin.has_add_permission(request),
|
|
|
|
can_change_related=related_modeladmin.has_change_permission(request),
|
|
|
|
can_delete_related=related_modeladmin.has_delete_permission(request),
|
|
|
|
)
|
2010-09-11 00:56:36 +08:00
|
|
|
formfield.widget = widgets.RelatedFieldWidgetWrapper(
|
2015-02-26 22:19:17 +08:00
|
|
|
formfield.widget, db_field.remote_field, self.admin_site, **wrapper_kwargs
|
2013-11-18 06:26:20 +08:00
|
|
|
)
|
2009-01-16 23:32:31 +08:00
|
|
|
|
|
|
|
return formfield
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-01-16 23:32:31 +08:00
|
|
|
# If we've got overrides for the formfield defined, use 'em. **kwargs
|
|
|
|
# passed to formfield_for_dbfield override the defaults.
|
2009-05-06 06:25:35 +08:00
|
|
|
for klass in db_field.__class__.mro():
|
|
|
|
if klass in self.formfield_overrides:
|
2012-12-08 19:41:11 +08:00
|
|
|
kwargs = dict(copy.deepcopy(self.formfield_overrides[klass]), **kwargs)
|
2009-05-06 06:25:35 +08:00
|
|
|
return db_field.formfield(**kwargs)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-01-16 23:32:31 +08:00
|
|
|
# For any other type of field, just call its formfield() method.
|
|
|
|
return db_field.formfield(**kwargs)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2015-12-24 23:25:59 +08:00
|
|
|
def formfield_for_choice_field(self, db_field, request, **kwargs):
|
2009-01-16 23:32:31 +08:00
|
|
|
"""
|
|
|
|
Get a form Field for a database Field that has declared choices.
|
|
|
|
"""
|
|
|
|
# If the field is named as a radio_field, use a RadioSelect
|
|
|
|
if db_field.name in self.radio_fields:
|
|
|
|
# Avoid stomping on custom widget/choices arguments.
|
|
|
|
if 'widget' not in kwargs:
|
2008-09-01 04:11:28 +08:00
|
|
|
kwargs['widget'] = widgets.AdminRadioSelect(attrs={
|
|
|
|
'class': get_ul_class(self.radio_fields[db_field.name]),
|
|
|
|
})
|
2009-01-16 23:32:31 +08:00
|
|
|
if 'choices' not in kwargs:
|
2008-09-01 04:11:28 +08:00
|
|
|
kwargs['choices'] = db_field.get_choices(
|
2012-12-23 03:00:08 +08:00
|
|
|
include_blank=db_field.blank,
|
2008-09-01 04:11:28 +08:00
|
|
|
blank_choice=[('', _('None'))]
|
2008-07-30 19:41:04 +08:00
|
|
|
)
|
2009-01-16 23:32:31 +08:00
|
|
|
return db_field.formfield(**kwargs)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2013-02-24 02:02:01 +08:00
|
|
|
def get_field_queryset(self, db, db_field, request):
|
|
|
|
"""
|
|
|
|
If the ModelAdmin specifies ordering, the queryset should respect that
|
|
|
|
ordering. Otherwise don't specify the queryset, let the field decide
|
|
|
|
(returns None in that case).
|
|
|
|
"""
|
2015-05-14 02:51:18 +08:00
|
|
|
related_admin = self.admin_site._registry.get(db_field.remote_field.model)
|
2013-02-24 02:02:01 +08:00
|
|
|
if related_admin is not None:
|
|
|
|
ordering = related_admin.get_ordering(request)
|
|
|
|
if ordering is not None and ordering != ():
|
2015-02-26 22:19:17 +08:00
|
|
|
return db_field.remote_field.model._default_manager.using(db).order_by(*ordering)
|
2013-02-24 02:02:01 +08:00
|
|
|
return None
|
|
|
|
|
2015-12-24 23:25:59 +08:00
|
|
|
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
2009-01-16 23:32:31 +08:00
|
|
|
"""
|
|
|
|
Get a form Field for a ForeignKey.
|
|
|
|
"""
|
2009-12-22 23:18:51 +08:00
|
|
|
db = kwargs.get('using')
|
2009-01-16 23:32:31 +08:00
|
|
|
if db_field.name in self.raw_id_fields:
|
2015-02-26 22:19:17 +08:00
|
|
|
kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.remote_field,
|
2011-08-02 07:38:11 +08:00
|
|
|
self.admin_site, using=db)
|
2009-01-16 23:32:31 +08:00
|
|
|
elif db_field.name in self.radio_fields:
|
|
|
|
kwargs['widget'] = widgets.AdminRadioSelect(attrs={
|
|
|
|
'class': get_ul_class(self.radio_fields[db_field.name]),
|
|
|
|
})
|
2013-05-17 22:33:36 +08:00
|
|
|
kwargs['empty_label'] = _('None') if db_field.blank else None
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2014-03-31 03:11:05 +08:00
|
|
|
if 'queryset' not in kwargs:
|
2013-11-22 05:18:52 +08:00
|
|
|
queryset = self.get_field_queryset(db, db_field, request)
|
|
|
|
if queryset is not None:
|
|
|
|
kwargs['queryset'] = queryset
|
2013-02-24 02:02:01 +08:00
|
|
|
|
2009-01-16 23:32:31 +08:00
|
|
|
return db_field.formfield(**kwargs)
|
|
|
|
|
2015-12-24 23:25:59 +08:00
|
|
|
def formfield_for_manytomany(self, db_field, request, **kwargs):
|
2009-01-16 23:32:31 +08:00
|
|
|
"""
|
|
|
|
Get a form Field for a ManyToManyField.
|
|
|
|
"""
|
2009-11-03 22:02:49 +08:00
|
|
|
# If it uses an intermediary model that isn't auto created, don't show
|
|
|
|
# a field in admin.
|
2015-02-26 22:19:17 +08:00
|
|
|
if not db_field.remote_field.through._meta.auto_created:
|
2009-01-16 23:32:31 +08:00
|
|
|
return None
|
2009-12-22 23:18:51 +08:00
|
|
|
db = kwargs.get('using')
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-01-16 23:32:31 +08:00
|
|
|
if db_field.name in self.raw_id_fields:
|
2015-02-26 22:19:17 +08:00
|
|
|
kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.remote_field,
|
2011-08-02 07:38:11 +08:00
|
|
|
self.admin_site, using=db)
|
2009-01-16 23:32:31 +08:00
|
|
|
elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
|
2014-09-04 20:15:09 +08:00
|
|
|
kwargs['widget'] = widgets.FilteredSelectMultiple(
|
|
|
|
db_field.verbose_name,
|
|
|
|
db_field.name in self.filter_vertical
|
|
|
|
)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2014-03-31 03:11:05 +08:00
|
|
|
if 'queryset' not in kwargs:
|
2013-11-22 05:18:52 +08:00
|
|
|
queryset = self.get_field_queryset(db, db_field, request)
|
|
|
|
if queryset is not None:
|
|
|
|
kwargs['queryset'] = queryset
|
2013-02-24 02:02:01 +08:00
|
|
|
|
2013-05-20 03:28:33 +08:00
|
|
|
form_field = db_field.formfield(**kwargs)
|
|
|
|
if isinstance(form_field.widget, SelectMultiple) and not isinstance(form_field.widget, CheckboxSelectMultiple):
|
|
|
|
msg = _('Hold down "Control", or "Command" on a Mac, to select more than one.')
|
|
|
|
help_text = form_field.help_text
|
|
|
|
form_field.help_text = string_concat(help_text, ' ', msg) if help_text else msg
|
|
|
|
return form_field
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2013-10-24 23:28:09 +08:00
|
|
|
def get_view_on_site_url(self, obj=None):
|
|
|
|
if obj is None or not self.view_on_site:
|
|
|
|
return None
|
|
|
|
|
|
|
|
if callable(self.view_on_site):
|
|
|
|
return self.view_on_site(obj)
|
2013-11-21 17:26:49 +08:00
|
|
|
elif self.view_on_site and hasattr(obj, 'get_absolute_url'):
|
2013-10-24 23:28:09 +08:00
|
|
|
# use the ContentType lookup if view_on_site is True
|
|
|
|
return reverse('admin:view_on_site', kwargs={
|
2014-02-02 02:30:54 +08:00
|
|
|
'content_type_id': get_content_type_for_model(obj).pk,
|
2013-10-24 23:28:09 +08:00
|
|
|
'object_id': obj.pk
|
|
|
|
})
|
|
|
|
|
2015-03-13 18:08:03 +08:00
|
|
|
def get_empty_value_display(self):
|
|
|
|
"""
|
|
|
|
Return the empty_value_display set on ModelAdmin or AdminSite.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
return mark_safe(self.empty_value_display)
|
|
|
|
except AttributeError:
|
|
|
|
return mark_safe(self.admin_site.empty_value_display)
|
|
|
|
|
2013-07-31 13:52:11 +08:00
|
|
|
def get_fields(self, request, obj=None):
|
|
|
|
"""
|
|
|
|
Hook for specifying fields.
|
|
|
|
"""
|
|
|
|
return self.fields
|
|
|
|
|
|
|
|
def get_fieldsets(self, request, obj=None):
|
|
|
|
"""
|
|
|
|
Hook for specifying fieldsets.
|
|
|
|
"""
|
|
|
|
if self.fieldsets:
|
|
|
|
return self.fieldsets
|
|
|
|
return [(None, {'fields': self.get_fields(request, obj)})]
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2011-06-12 21:04:53 +08:00
|
|
|
def get_ordering(self, request):
|
|
|
|
"""
|
|
|
|
Hook for specifying field ordering.
|
|
|
|
"""
|
|
|
|
return self.ordering or () # otherwise we might try to *None, which is bad ;)
|
|
|
|
|
2009-12-23 02:29:00 +08:00
|
|
|
def get_readonly_fields(self, request, obj=None):
|
2011-04-22 20:02:25 +08:00
|
|
|
"""
|
|
|
|
Hook for specifying custom readonly fields.
|
|
|
|
"""
|
2009-12-23 02:29:00 +08:00
|
|
|
return self.readonly_fields
|
|
|
|
|
2011-04-22 20:02:25 +08:00
|
|
|
def get_prepopulated_fields(self, request, obj=None):
|
|
|
|
"""
|
|
|
|
Hook for specifying custom prepopulated fields.
|
|
|
|
"""
|
|
|
|
return self.prepopulated_fields
|
|
|
|
|
2013-03-08 22:15:23 +08:00
|
|
|
def get_queryset(self, request):
|
2010-12-13 06:56:01 +08:00
|
|
|
"""
|
|
|
|
Returns a QuerySet of all model instances that can be edited by the
|
|
|
|
admin site. This is used by changelist_view.
|
|
|
|
"""
|
2013-03-08 22:15:23 +08:00
|
|
|
qs = self.model._default_manager.get_queryset()
|
2010-12-13 06:56:01 +08:00
|
|
|
# TODO: this should be handled by some parameter to the ChangeList.
|
2011-06-12 21:04:53 +08:00
|
|
|
ordering = self.get_ordering(request)
|
2010-12-13 06:56:01 +08:00
|
|
|
if ordering:
|
|
|
|
qs = qs.order_by(*ordering)
|
|
|
|
return qs
|
|
|
|
|
2011-01-28 22:08:25 +08:00
|
|
|
def lookup_allowed(self, lookup, value):
|
2013-09-27 02:25:30 +08:00
|
|
|
from django.contrib.admin.filters import SimpleListFilter
|
|
|
|
|
2011-01-28 22:08:25 +08:00
|
|
|
model = self.model
|
|
|
|
# Check FKey lookups that are allowed, so that popups produced by
|
|
|
|
# ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
|
|
|
|
# are allowed to work.
|
|
|
|
for l in model._meta.related_fkey_lookups:
|
2014-02-02 03:23:31 +08:00
|
|
|
# As ``limit_choices_to`` can be a callable, invoke it here.
|
|
|
|
if callable(l):
|
|
|
|
l = l()
|
2011-01-28 22:08:25 +08:00
|
|
|
for k, v in widgets.url_params_from_lookup_dict(l).items():
|
|
|
|
if k == lookup and v == value:
|
|
|
|
return True
|
|
|
|
|
2015-02-26 22:19:17 +08:00
|
|
|
relation_parts = []
|
|
|
|
prev_field = None
|
|
|
|
for part in lookup.split(LOOKUP_SEP):
|
2012-03-18 05:45:36 +08:00
|
|
|
try:
|
2015-01-07 08:16:35 +08:00
|
|
|
field = model._meta.get_field(part)
|
2012-03-18 05:45:36 +08:00
|
|
|
except FieldDoesNotExist:
|
2013-03-29 01:16:53 +08:00
|
|
|
# Lookups on non-existent fields are ok, since they're ignored
|
2012-03-18 05:45:36 +08:00
|
|
|
# later.
|
2015-02-26 22:19:17 +08:00
|
|
|
break
|
|
|
|
# It is allowed to filter on values that would be found from local
|
|
|
|
# model anyways. For example, if you filter on employee__department__id,
|
|
|
|
# then the id value would be found already from employee__department_id.
|
|
|
|
if not prev_field or (prev_field.concrete and
|
|
|
|
field not in prev_field.get_path_info()[-1].target_fields):
|
|
|
|
relation_parts.append(part)
|
|
|
|
if not getattr(field, 'get_path_info', None):
|
|
|
|
# This is not a relational field, so further parts
|
|
|
|
# must be transforms.
|
|
|
|
break
|
|
|
|
prev_field = field
|
|
|
|
model = field.get_path_info()[-1].to_opts.model
|
|
|
|
|
|
|
|
if len(relation_parts) <= 1:
|
|
|
|
# Either a local field filter, or no fields at all.
|
2010-12-23 11:44:38 +08:00
|
|
|
return True
|
2015-02-26 22:19:17 +08:00
|
|
|
clean_lookup = LOOKUP_SEP.join(relation_parts)
|
2013-09-27 02:25:30 +08:00
|
|
|
valid_lookups = [self.date_hierarchy]
|
|
|
|
for filter_item in self.list_filter:
|
|
|
|
if isinstance(filter_item, type) and issubclass(filter_item, SimpleListFilter):
|
|
|
|
valid_lookups.append(filter_item.parameter_name)
|
|
|
|
elif isinstance(filter_item, (list, tuple)):
|
|
|
|
valid_lookups.append(filter_item[0])
|
|
|
|
else:
|
|
|
|
valid_lookups.append(filter_item)
|
|
|
|
return clean_lookup in valid_lookups
|
2010-12-23 11:44:38 +08:00
|
|
|
|
2014-08-07 12:18:10 +08:00
|
|
|
def to_field_allowed(self, request, to_field):
|
2014-09-05 05:04:53 +08:00
|
|
|
"""
|
|
|
|
Returns True if the model associated with this admin should be
|
|
|
|
allowed to be referenced by the specified field.
|
|
|
|
"""
|
2014-08-07 12:18:10 +08:00
|
|
|
opts = self.model._meta
|
|
|
|
|
|
|
|
try:
|
|
|
|
field = opts.get_field(to_field)
|
|
|
|
except FieldDoesNotExist:
|
|
|
|
return False
|
|
|
|
|
2014-11-16 23:42:09 +08:00
|
|
|
# Always allow referencing the primary key since it's already possible
|
|
|
|
# to get this information from the change view URL.
|
|
|
|
if field.primary_key:
|
2014-10-06 02:06:51 +08:00
|
|
|
return True
|
|
|
|
|
2014-11-26 03:27:46 +08:00
|
|
|
# Allow reverse relationships to models defining m2m fields if they
|
|
|
|
# target the specified field.
|
|
|
|
for many_to_many in opts.many_to_many:
|
|
|
|
if many_to_many.m2m_target_field_name() == to_field:
|
|
|
|
return True
|
|
|
|
|
2014-08-07 12:18:10 +08:00
|
|
|
# Make sure at least one of the models registered for this site
|
2014-08-21 23:55:23 +08:00
|
|
|
# references this field through a FK or a M2M relationship.
|
2014-09-05 05:04:53 +08:00
|
|
|
registered_models = set()
|
|
|
|
for model, admin in self.admin_site._registry.items():
|
|
|
|
registered_models.add(model)
|
|
|
|
for inline in admin.inlines:
|
|
|
|
registered_models.add(inline.model)
|
|
|
|
|
2015-01-07 08:16:35 +08:00
|
|
|
related_objects = (
|
|
|
|
f for f in opts.get_fields(include_hidden=True)
|
|
|
|
if (f.auto_created and not f.concrete)
|
|
|
|
)
|
|
|
|
for related_object in related_objects:
|
|
|
|
related_model = related_object.related_model
|
2015-10-28 23:25:25 +08:00
|
|
|
remote_field = related_object.field.remote_field
|
2014-08-21 23:55:23 +08:00
|
|
|
if (any(issubclass(model, related_model) for model in registered_models) and
|
2015-10-28 23:25:25 +08:00
|
|
|
hasattr(remote_field, 'get_related_field') and
|
|
|
|
remote_field.get_related_field() == field):
|
2014-08-07 12:18:10 +08:00
|
|
|
return True
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
2011-10-07 08:41:25 +08:00
|
|
|
def has_add_permission(self, request):
|
|
|
|
"""
|
|
|
|
Returns True if the given request has permission to add an object.
|
2013-03-29 01:16:53 +08:00
|
|
|
Can be overridden by the user in subclasses.
|
2011-10-07 08:41:25 +08:00
|
|
|
"""
|
|
|
|
opts = self.opts
|
2013-06-23 09:48:09 +08:00
|
|
|
codename = get_permission_codename('add', opts)
|
|
|
|
return request.user.has_perm("%s.%s" % (opts.app_label, codename))
|
2011-10-07 08:41:25 +08:00
|
|
|
|
|
|
|
def has_change_permission(self, request, obj=None):
|
|
|
|
"""
|
|
|
|
Returns True if the given request has permission to change the given
|
|
|
|
Django model instance, the default implementation doesn't examine the
|
|
|
|
`obj` parameter.
|
|
|
|
|
2013-03-29 01:16:53 +08:00
|
|
|
Can be overridden by the user in subclasses. In such case it should
|
2011-10-07 08:41:25 +08:00
|
|
|
return True if the given request has permission to change the `obj`
|
|
|
|
model instance. If `obj` is None, this should return True if the given
|
|
|
|
request has permission to change *any* object of the given type.
|
|
|
|
"""
|
|
|
|
opts = self.opts
|
2013-06-23 09:48:09 +08:00
|
|
|
codename = get_permission_codename('change', opts)
|
|
|
|
return request.user.has_perm("%s.%s" % (opts.app_label, codename))
|
2011-10-07 08:41:25 +08:00
|
|
|
|
|
|
|
def has_delete_permission(self, request, obj=None):
|
|
|
|
"""
|
|
|
|
Returns True if the given request has permission to change the given
|
|
|
|
Django model instance, the default implementation doesn't examine the
|
|
|
|
`obj` parameter.
|
|
|
|
|
2013-03-29 01:16:53 +08:00
|
|
|
Can be overridden by the user in subclasses. In such case it should
|
2011-10-07 08:41:25 +08:00
|
|
|
return True if the given request has permission to delete the `obj`
|
|
|
|
model instance. If `obj` is None, this should return True if the given
|
|
|
|
request has permission to delete *any* object of the given type.
|
|
|
|
"""
|
|
|
|
opts = self.opts
|
2013-06-23 09:48:09 +08:00
|
|
|
codename = get_permission_codename('delete', opts)
|
|
|
|
return request.user.has_perm("%s.%s" % (opts.app_label, codename))
|
|
|
|
|
2014-05-29 00:07:27 +08:00
|
|
|
def has_module_permission(self, request):
|
|
|
|
"""
|
|
|
|
Returns True if the given request has any permission in the given
|
|
|
|
app label.
|
|
|
|
|
|
|
|
Can be overridden by the user in subclasses. In such case it should
|
|
|
|
return True if the given request has permission to view the module on
|
|
|
|
the admin index page and access the module's index page. Overriding it
|
|
|
|
does not restrict access to the add, change or delete views. Use
|
|
|
|
`ModelAdmin.has_(add|change|delete)_permission` for that.
|
|
|
|
"""
|
|
|
|
return request.user.has_module_perms(self.opts.app_label)
|
|
|
|
|
2011-06-12 21:04:53 +08:00
|
|
|
|
2014-01-20 10:45:21 +08:00
|
|
|
@python_2_unicode_compatible
|
2008-07-19 07:54:34 +08:00
|
|
|
class ModelAdmin(BaseModelAdmin):
|
|
|
|
"Encapsulates all admin options and functionality for a given model."
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
list_display = ('__str__',)
|
|
|
|
list_display_links = ()
|
|
|
|
list_filter = ()
|
|
|
|
list_select_related = False
|
|
|
|
list_per_page = 100
|
2011-09-08 21:25:00 +08:00
|
|
|
list_max_show_all = 200
|
2009-03-18 04:51:47 +08:00
|
|
|
list_editable = ()
|
2008-07-19 07:54:34 +08:00
|
|
|
search_fields = ()
|
|
|
|
date_hierarchy = None
|
|
|
|
save_as = False
|
|
|
|
save_on_top = False
|
2010-12-21 22:57:29 +08:00
|
|
|
paginator = Paginator
|
2013-06-19 03:41:36 +08:00
|
|
|
preserve_filters = True
|
2008-07-19 07:54:34 +08:00
|
|
|
inlines = []
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
# Custom templates (designed to be over-ridden in subclasses)
|
2010-01-13 07:34:03 +08:00
|
|
|
add_form_template = None
|
2008-07-19 07:54:34 +08:00
|
|
|
change_form_template = None
|
|
|
|
change_list_template = None
|
|
|
|
delete_confirmation_template = None
|
2010-04-05 20:02:27 +08:00
|
|
|
delete_selected_confirmation_template = None
|
2008-07-19 07:54:34 +08:00
|
|
|
object_history_template = None
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-03-24 04:22:56 +08:00
|
|
|
# Actions
|
2009-04-07 04:23:33 +08:00
|
|
|
actions = []
|
2009-03-24 04:22:56 +08:00
|
|
|
action_form = helpers.ActionForm
|
|
|
|
actions_on_top = True
|
|
|
|
actions_on_bottom = False
|
2010-01-06 02:24:27 +08:00
|
|
|
actions_selection_counter = True
|
2014-01-20 10:45:21 +08:00
|
|
|
checks_class = ModelAdminChecks
|
2013-02-23 23:10:32 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def __init__(self, model, admin_site):
|
|
|
|
self.model = model
|
|
|
|
self.opts = model._meta
|
|
|
|
self.admin_site = admin_site
|
|
|
|
super(ModelAdmin, self).__init__()
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2014-01-20 10:45:21 +08:00
|
|
|
def __str__(self):
|
|
|
|
return "%s.%s" % (self.model._meta.app_label, self.__class__.__name__)
|
|
|
|
|
2012-10-20 21:48:38 +08:00
|
|
|
def get_inline_instances(self, request, obj=None):
|
2011-10-07 08:41:25 +08:00
|
|
|
inline_instances = []
|
|
|
|
for inline_class in self.inlines:
|
|
|
|
inline = inline_class(self.model, self.admin_site)
|
|
|
|
if request:
|
|
|
|
if not (inline.has_add_permission(request) or
|
2012-10-20 21:48:38 +08:00
|
|
|
inline.has_change_permission(request, obj) or
|
|
|
|
inline.has_delete_permission(request, obj)):
|
2011-10-07 08:41:25 +08:00
|
|
|
continue
|
|
|
|
if not inline.has_add_permission(request):
|
|
|
|
inline.max_num = 0
|
|
|
|
inline_instances.append(inline)
|
|
|
|
|
|
|
|
return inline_instances
|
|
|
|
|
2009-01-15 04:22:25 +08:00
|
|
|
def get_urls(self):
|
2014-04-02 08:46:34 +08:00
|
|
|
from django.conf.urls import url
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-01-15 04:22:25 +08:00
|
|
|
def wrap(view):
|
|
|
|
def wrapper(*args, **kwargs):
|
|
|
|
return self.admin_site.admin_view(view)(*args, **kwargs)
|
2014-12-27 15:16:53 +08:00
|
|
|
wrapper.model_admin = self
|
2009-01-15 04:22:25 +08:00
|
|
|
return update_wrapper(wrapper, view)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2013-02-05 17:16:07 +08:00
|
|
|
info = self.model._meta.app_label, self.model._meta.model_name
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2014-04-02 08:46:34 +08:00
|
|
|
urlpatterns = [
|
2013-09-07 01:15:09 +08:00
|
|
|
url(r'^$', wrap(self.changelist_view), name='%s_%s_changelist' % info),
|
|
|
|
url(r'^add/$', wrap(self.add_view), name='%s_%s_add' % info),
|
|
|
|
url(r'^(.+)/history/$', wrap(self.history_view), name='%s_%s_history' % info),
|
|
|
|
url(r'^(.+)/delete/$', wrap(self.delete_view), name='%s_%s_delete' % info),
|
2015-02-08 00:55:47 +08:00
|
|
|
url(r'^(.+)/change/$', wrap(self.change_view), name='%s_%s_change' % info),
|
|
|
|
# For backwards compatibility (was the change url before 1.9)
|
|
|
|
url(r'^(.+)/$', wrap(RedirectView.as_view(
|
|
|
|
pattern_name='%s:%s_%s_change' % ((self.admin_site.name,) + info)
|
|
|
|
))),
|
2014-04-02 08:46:34 +08:00
|
|
|
]
|
2009-01-15 04:22:25 +08:00
|
|
|
return urlpatterns
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-01-15 04:22:25 +08:00
|
|
|
def urls(self):
|
|
|
|
return self.get_urls()
|
|
|
|
urls = property(urls)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2011-08-11 22:07:39 +08:00
|
|
|
@property
|
|
|
|
def media(self):
|
2012-02-05 18:26:05 +08:00
|
|
|
extra = '' if settings.DEBUG else '.min'
|
2011-06-30 17:06:19 +08:00
|
|
|
js = [
|
|
|
|
'core.js',
|
2015-06-07 07:32:54 +08:00
|
|
|
'vendor/jquery/jquery%s.js' % extra,
|
2015-03-11 18:12:14 +08:00
|
|
|
'jquery.init.js',
|
2015-11-23 18:46:19 +08:00
|
|
|
'admin/RelatedObjectLookups.js',
|
2015-03-11 18:12:14 +08:00
|
|
|
'actions%s.js' % extra,
|
|
|
|
'urlify.js',
|
|
|
|
'prepopulate%s.js' % extra,
|
2015-04-16 06:28:49 +08:00
|
|
|
'vendor/xregexp/xregexp.min.js',
|
2011-06-30 17:06:19 +08:00
|
|
|
]
|
2015-11-07 19:24:38 +08:00
|
|
|
return forms.Media(js=['admin/js/%s' % url for url in js])
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-04-09 03:47:46 +08:00
|
|
|
def get_model_perms(self, request):
|
|
|
|
"""
|
|
|
|
Returns a dict of all perms for this model. This dict has the keys
|
|
|
|
``add``, ``change``, and ``delete`` mapping to the True/False for each
|
|
|
|
of those actions.
|
|
|
|
"""
|
|
|
|
return {
|
|
|
|
'add': self.has_add_permission(request),
|
|
|
|
'change': self.has_change_permission(request),
|
|
|
|
'delete': self.has_delete_permission(request),
|
|
|
|
}
|
|
|
|
|
2013-07-31 13:52:11 +08:00
|
|
|
def get_fields(self, request, obj=None):
|
|
|
|
if self.fields:
|
|
|
|
return self.fields
|
2013-04-17 02:49:22 +08:00
|
|
|
form = self.get_form(request, obj, fields=None)
|
2013-07-31 13:52:11 +08:00
|
|
|
return list(form.base_fields) + list(self.get_readonly_fields(request, obj))
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-08-16 05:57:36 +08:00
|
|
|
def get_form(self, request, obj=None, **kwargs):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
|
|
|
Returns a Form class for use in the admin add view. This is used by
|
|
|
|
add_view and change_view.
|
|
|
|
"""
|
2013-04-17 02:49:22 +08:00
|
|
|
if 'fields' in kwargs:
|
|
|
|
fields = kwargs.pop('fields')
|
2008-07-19 07:54:34 +08:00
|
|
|
else:
|
2013-04-17 02:49:22 +08:00
|
|
|
fields = flatten_fieldsets(self.get_fieldsets(request, obj))
|
2008-09-03 01:26:24 +08:00
|
|
|
if self.exclude is None:
|
|
|
|
exclude = []
|
|
|
|
else:
|
2008-09-27 13:57:10 +08:00
|
|
|
exclude = list(self.exclude)
|
2015-06-06 09:29:07 +08:00
|
|
|
readonly_fields = self.get_readonly_fields(request, obj)
|
|
|
|
exclude.extend(readonly_fields)
|
2011-08-12 22:14:49 +08:00
|
|
|
if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
|
|
|
|
# Take the custom ModelForm's Meta.exclude into account only if the
|
|
|
|
# ModelAdmin doesn't define its own.
|
|
|
|
exclude.extend(self.form._meta.exclude)
|
2013-03-28 23:10:13 +08:00
|
|
|
# if exclude is an empty list we pass None to be consistent with the
|
2009-04-22 23:48:51 +08:00
|
|
|
# default on modelform_factory
|
2009-12-23 02:29:00 +08:00
|
|
|
exclude = exclude or None
|
2015-06-06 09:29:07 +08:00
|
|
|
|
|
|
|
# Remove declared form fields which are in readonly_fields.
|
|
|
|
new_attrs = OrderedDict(
|
|
|
|
(f, None) for f in readonly_fields
|
|
|
|
if f in self.form.declared_fields
|
|
|
|
)
|
|
|
|
form = type(self.form.__name__, (self.form,), new_attrs)
|
|
|
|
|
2008-08-16 05:57:36 +08:00
|
|
|
defaults = {
|
2015-06-06 09:29:07 +08:00
|
|
|
"form": form,
|
2008-08-16 05:57:36 +08:00
|
|
|
"fields": fields,
|
2009-12-23 02:29:00 +08:00
|
|
|
"exclude": exclude,
|
2011-03-28 09:40:43 +08:00
|
|
|
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
|
2008-08-16 05:57:36 +08:00
|
|
|
}
|
|
|
|
defaults.update(kwargs)
|
2013-02-22 05:56:55 +08:00
|
|
|
|
|
|
|
if defaults['fields'] is None and not modelform_defines_fields(defaults['form']):
|
|
|
|
defaults['fields'] = forms.ALL_FIELDS
|
|
|
|
|
2013-05-09 07:49:05 +08:00
|
|
|
try:
|
|
|
|
return modelform_factory(self.model, **defaults)
|
|
|
|
except FieldError as e:
|
|
|
|
raise FieldError('%s. Check fields/fieldsets/exclude attributes of class %s.'
|
|
|
|
% (e, self.__class__.__name__))
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-12-18 18:08:05 +08:00
|
|
|
def get_changelist(self, request, **kwargs):
|
|
|
|
"""
|
|
|
|
Returns the ChangeList class for use on the changelist page.
|
|
|
|
"""
|
|
|
|
from django.contrib.admin.views.main import ChangeList
|
|
|
|
return ChangeList
|
|
|
|
|
2013-11-18 06:26:20 +08:00
|
|
|
def get_object(self, request, object_id, from_field=None):
|
2009-12-28 22:08:11 +08:00
|
|
|
"""
|
2013-11-18 06:26:20 +08:00
|
|
|
Returns an instance matching the field and value provided, the primary
|
|
|
|
key is used if no field is provided. Returns ``None`` if no match is
|
|
|
|
found or the object_id fails validation.
|
2009-12-28 22:08:11 +08:00
|
|
|
"""
|
2013-03-08 22:15:23 +08:00
|
|
|
queryset = self.get_queryset(request)
|
2009-12-28 22:08:11 +08:00
|
|
|
model = queryset.model
|
2013-11-18 06:26:20 +08:00
|
|
|
field = model._meta.pk if from_field is None else model._meta.get_field(from_field)
|
2009-12-28 22:08:11 +08:00
|
|
|
try:
|
2013-11-18 06:26:20 +08:00
|
|
|
object_id = field.to_python(object_id)
|
|
|
|
return queryset.get(**{field.name: object_id})
|
2013-03-01 13:01:25 +08:00
|
|
|
except (model.DoesNotExist, ValidationError, ValueError):
|
2009-12-28 22:08:11 +08:00
|
|
|
return None
|
|
|
|
|
2009-03-18 04:51:47 +08:00
|
|
|
def get_changelist_form(self, request, **kwargs):
|
|
|
|
"""
|
|
|
|
Returns a Form class for use in the Formset on the changelist page.
|
|
|
|
"""
|
|
|
|
defaults = {
|
2011-03-28 09:40:43 +08:00
|
|
|
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
|
2009-03-18 04:51:47 +08:00
|
|
|
}
|
|
|
|
defaults.update(kwargs)
|
2013-02-22 05:56:55 +08:00
|
|
|
if (defaults.get('fields') is None
|
2013-11-26 17:43:46 +08:00
|
|
|
and not modelform_defines_fields(defaults.get('form'))):
|
2013-02-22 05:56:55 +08:00
|
|
|
defaults['fields'] = forms.ALL_FIELDS
|
|
|
|
|
2009-03-18 04:51:47 +08:00
|
|
|
return modelform_factory(self.model, **defaults)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-03-18 04:51:47 +08:00
|
|
|
def get_changelist_formset(self, request, **kwargs):
|
|
|
|
"""
|
2009-03-18 17:19:24 +08:00
|
|
|
Returns a FormSet class for use on the changelist page if list_editable
|
2009-03-18 04:51:47 +08:00
|
|
|
is used.
|
|
|
|
"""
|
|
|
|
defaults = {
|
2011-03-28 09:40:43 +08:00
|
|
|
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
|
2009-03-18 04:51:47 +08:00
|
|
|
}
|
|
|
|
defaults.update(kwargs)
|
2009-03-18 17:19:24 +08:00
|
|
|
return modelformset_factory(self.model,
|
|
|
|
self.get_changelist_form(request), extra=0,
|
2009-03-18 04:51:47 +08:00
|
|
|
fields=self.list_editable, **defaults)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2013-09-04 09:01:45 +08:00
|
|
|
def get_formsets_with_inlines(self, request, obj=None):
|
|
|
|
"""
|
|
|
|
Yields formsets and the corresponding inlines.
|
|
|
|
"""
|
2015-01-18 07:02:35 +08:00
|
|
|
for inline in self.get_inline_instances(request, obj):
|
|
|
|
yield inline.get_formset(request, obj), inline
|
2013-09-04 09:01:45 +08:00
|
|
|
|
2010-12-22 03:19:04 +08:00
|
|
|
def get_paginator(self, request, queryset, per_page, orphans=0, allow_empty_first_page=True):
|
|
|
|
return self.paginator(queryset, per_page, orphans, allow_empty_first_page)
|
|
|
|
|
2015-03-17 05:55:44 +08:00
|
|
|
def log_addition(self, request, object, message):
|
2008-08-10 00:45:15 +08:00
|
|
|
"""
|
2009-01-15 04:22:25 +08:00
|
|
|
Log that an object has been successfully added.
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-08-10 00:45:15 +08:00
|
|
|
The default implementation creates an admin LogEntry object.
|
|
|
|
"""
|
|
|
|
from django.contrib.admin.models import LogEntry, ADDITION
|
|
|
|
LogEntry.objects.log_action(
|
2013-06-23 09:48:09 +08:00
|
|
|
user_id=request.user.pk,
|
2014-02-02 02:30:54 +08:00
|
|
|
content_type_id=get_content_type_for_model(object).pk,
|
2013-06-23 09:48:09 +08:00
|
|
|
object_id=object.pk,
|
|
|
|
object_repr=force_text(object),
|
2015-03-17 05:55:44 +08:00
|
|
|
action_flag=ADDITION,
|
|
|
|
change_message=message,
|
2008-08-10 00:45:15 +08:00
|
|
|
)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-08-10 00:45:15 +08:00
|
|
|
def log_change(self, request, object, message):
|
|
|
|
"""
|
2009-01-15 04:22:25 +08:00
|
|
|
Log that an object has been successfully changed.
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-08-10 00:45:15 +08:00
|
|
|
The default implementation creates an admin LogEntry object.
|
|
|
|
"""
|
|
|
|
from django.contrib.admin.models import LogEntry, CHANGE
|
|
|
|
LogEntry.objects.log_action(
|
2013-06-23 09:48:09 +08:00
|
|
|
user_id=request.user.pk,
|
2014-02-02 02:30:54 +08:00
|
|
|
content_type_id=get_content_type_for_model(object).pk,
|
2013-06-23 09:48:09 +08:00
|
|
|
object_id=object.pk,
|
|
|
|
object_repr=force_text(object),
|
|
|
|
action_flag=CHANGE,
|
2015-03-17 05:55:44 +08:00
|
|
|
change_message=message,
|
2008-08-10 00:45:15 +08:00
|
|
|
)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-08-10 00:45:15 +08:00
|
|
|
def log_deletion(self, request, object, object_repr):
|
|
|
|
"""
|
2014-02-09 20:29:29 +08:00
|
|
|
Log that an object will be deleted. Note that this method must be
|
|
|
|
called before the deletion.
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-08-10 00:45:15 +08:00
|
|
|
The default implementation creates an admin LogEntry object.
|
|
|
|
"""
|
|
|
|
from django.contrib.admin.models import LogEntry, DELETION
|
|
|
|
LogEntry.objects.log_action(
|
2013-06-23 09:48:09 +08:00
|
|
|
user_id=request.user.pk,
|
2014-02-09 20:29:29 +08:00
|
|
|
content_type_id=get_content_type_for_model(object).pk,
|
2013-06-23 09:48:09 +08:00
|
|
|
object_id=object.pk,
|
|
|
|
object_repr=object_repr,
|
2015-03-17 05:55:44 +08:00
|
|
|
action_flag=DELETION,
|
2008-08-10 00:45:15 +08:00
|
|
|
)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-03-24 04:22:56 +08:00
|
|
|
def action_checkbox(self, obj):
|
|
|
|
"""
|
|
|
|
A list_display column containing a checkbox widget.
|
|
|
|
"""
|
2012-07-21 16:00:10 +08:00
|
|
|
return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, force_text(obj.pk))
|
2009-03-24 04:22:56 +08:00
|
|
|
action_checkbox.short_description = mark_safe('<input type="checkbox" id="action-toggle" />')
|
|
|
|
|
2009-04-07 04:23:33 +08:00
|
|
|
def get_actions(self, request):
|
2009-03-24 04:22:56 +08:00
|
|
|
"""
|
|
|
|
Return a dictionary mapping the names of all actions for this
|
|
|
|
ModelAdmin to a tuple of (callable, name, description) for each action.
|
|
|
|
"""
|
2013-03-29 01:16:53 +08:00
|
|
|
# If self.actions is explicitly set to None that means that we don't
|
2009-04-07 04:23:33 +08:00
|
|
|
# want *any* actions enabled on this page.
|
2014-03-21 23:35:33 +08:00
|
|
|
if self.actions is None or IS_POPUP_VAR in request.GET:
|
2013-08-03 13:41:15 +08:00
|
|
|
return OrderedDict()
|
2009-05-06 06:25:35 +08:00
|
|
|
|
2009-04-07 04:23:33 +08:00
|
|
|
actions = []
|
2009-05-06 06:25:35 +08:00
|
|
|
|
2009-04-07 04:23:33 +08:00
|
|
|
# Gather actions from the admin site first
|
|
|
|
for (name, func) in self.admin_site.actions:
|
|
|
|
description = getattr(func, 'short_description', name.replace('_', ' '))
|
|
|
|
actions.append((func, name, description))
|
2009-05-06 06:25:35 +08:00
|
|
|
|
|
|
|
# Then gather them from the model admin and all parent classes,
|
2009-04-07 04:23:33 +08:00
|
|
|
# starting with self and working back up.
|
|
|
|
for klass in self.__class__.mro()[::-1]:
|
|
|
|
class_actions = getattr(klass, 'actions', [])
|
|
|
|
# Avoid trying to iterate over None
|
|
|
|
if not class_actions:
|
2009-05-06 06:25:35 +08:00
|
|
|
continue
|
2013-08-30 07:20:00 +08:00
|
|
|
actions.extend(self.get_action(action) for action in class_actions)
|
2009-05-06 06:25:35 +08:00
|
|
|
|
2009-04-07 04:23:33 +08:00
|
|
|
# get_action might have returned None, so filter any of those out.
|
|
|
|
actions = filter(None, actions)
|
2009-05-06 06:25:35 +08:00
|
|
|
|
2013-08-03 13:41:15 +08:00
|
|
|
# Convert the actions into an OrderedDict keyed by name.
|
2013-08-30 07:20:00 +08:00
|
|
|
actions = OrderedDict(
|
2009-04-07 04:23:33 +08:00
|
|
|
(name, (func, name, desc))
|
|
|
|
for func, name, desc in actions
|
2013-08-30 07:20:00 +08:00
|
|
|
)
|
2009-05-06 06:25:35 +08:00
|
|
|
|
2009-03-24 04:22:56 +08:00
|
|
|
return actions
|
|
|
|
|
2009-04-07 04:23:33 +08:00
|
|
|
def get_action_choices(self, request, default_choices=BLANK_CHOICE_DASH):
|
2009-03-24 04:22:56 +08:00
|
|
|
"""
|
|
|
|
Return a list of choices for use in a form object. Each choice is a
|
|
|
|
tuple (name, description).
|
|
|
|
"""
|
|
|
|
choices = [] + default_choices
|
2012-07-21 03:14:27 +08:00
|
|
|
for func, name, description in six.itervalues(self.get_actions(request)):
|
2009-03-24 04:22:56 +08:00
|
|
|
choice = (name, description % model_format_dict(self.opts))
|
|
|
|
choices.append(choice)
|
|
|
|
return choices
|
|
|
|
|
|
|
|
def get_action(self, action):
|
|
|
|
"""
|
2009-08-14 01:04:42 +08:00
|
|
|
Return a given action from a parameter, which can either be a callable,
|
2009-03-24 04:22:56 +08:00
|
|
|
or the name of a method on the ModelAdmin. Return is a tuple of
|
|
|
|
(callable, name, description).
|
|
|
|
"""
|
2009-04-07 04:23:33 +08:00
|
|
|
# If the action is a callable, just use it.
|
2009-03-24 04:22:56 +08:00
|
|
|
if callable(action):
|
|
|
|
func = action
|
|
|
|
action = action.__name__
|
2009-05-06 06:25:35 +08:00
|
|
|
|
2009-04-07 04:23:33 +08:00
|
|
|
# Next, look for a method. Grab it off self.__class__ to get an unbound
|
|
|
|
# method instead of a bound one; this ensures that the calling
|
|
|
|
# conventions are the same for functions and methods.
|
|
|
|
elif hasattr(self.__class__, action):
|
|
|
|
func = getattr(self.__class__, action)
|
2009-05-06 06:25:35 +08:00
|
|
|
|
2009-04-07 04:23:33 +08:00
|
|
|
# Finally, look for a named method on the admin site
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
func = self.admin_site.get_action(action)
|
|
|
|
except KeyError:
|
|
|
|
return None
|
2009-05-06 06:25:35 +08:00
|
|
|
|
2009-03-24 04:22:56 +08:00
|
|
|
if hasattr(func, 'short_description'):
|
|
|
|
description = func.short_description
|
|
|
|
else:
|
|
|
|
description = capfirst(action.replace('_', ' '))
|
|
|
|
return func, action, description
|
|
|
|
|
2011-06-09 06:53:55 +08:00
|
|
|
def get_list_display(self, request):
|
|
|
|
"""
|
|
|
|
Return a sequence containing the fields to be displayed on the
|
|
|
|
changelist.
|
|
|
|
"""
|
|
|
|
return self.list_display
|
|
|
|
|
2011-10-26 20:19:18 +08:00
|
|
|
def get_list_display_links(self, request, list_display):
|
|
|
|
"""
|
|
|
|
Return a sequence containing the fields to be displayed as links
|
|
|
|
on the changelist. The list_display parameter is the list of fields
|
|
|
|
returned by get_list_display().
|
|
|
|
"""
|
2013-09-07 02:25:13 +08:00
|
|
|
if self.list_display_links or self.list_display_links is None or not list_display:
|
2011-10-26 20:19:18 +08:00
|
|
|
return self.list_display_links
|
|
|
|
else:
|
|
|
|
# Use only the first item in list_display as link
|
|
|
|
return list(list_display)[:1]
|
|
|
|
|
2012-11-26 03:39:23 +08:00
|
|
|
def get_list_filter(self, request):
|
|
|
|
"""
|
|
|
|
Returns a sequence containing the fields to be displayed as filters in
|
|
|
|
the right sidebar of the changelist page.
|
|
|
|
"""
|
|
|
|
return self.list_filter
|
|
|
|
|
2015-03-16 18:00:16 +08:00
|
|
|
def get_list_select_related(self, request):
|
|
|
|
"""
|
|
|
|
Returns a list of fields to add to the select_related() part of the
|
|
|
|
changelist items query.
|
|
|
|
"""
|
|
|
|
return self.list_select_related
|
|
|
|
|
2013-08-04 00:15:15 +08:00
|
|
|
def get_search_fields(self, request):
|
|
|
|
"""
|
|
|
|
Returns a sequence containing the fields to be searched whenever
|
|
|
|
somebody submits a search query.
|
|
|
|
"""
|
|
|
|
return self.search_fields
|
|
|
|
|
2013-08-04 18:18:17 +08:00
|
|
|
def get_search_results(self, request, queryset, search_term):
|
|
|
|
"""
|
|
|
|
Returns a tuple containing a queryset to implement the search,
|
|
|
|
and a boolean indicating if the results may contain duplicates.
|
|
|
|
"""
|
|
|
|
# Apply keyword searches.
|
|
|
|
def construct_search(field_name):
|
|
|
|
if field_name.startswith('^'):
|
|
|
|
return "%s__istartswith" % field_name[1:]
|
|
|
|
elif field_name.startswith('='):
|
|
|
|
return "%s__iexact" % field_name[1:]
|
|
|
|
elif field_name.startswith('@'):
|
|
|
|
return "%s__search" % field_name[1:]
|
|
|
|
else:
|
|
|
|
return "%s__icontains" % field_name
|
|
|
|
|
|
|
|
use_distinct = False
|
|
|
|
search_fields = self.get_search_fields(request)
|
|
|
|
if search_fields and search_term:
|
|
|
|
orm_lookups = [construct_search(str(search_field))
|
|
|
|
for search_field in search_fields]
|
|
|
|
for bit in search_term.split():
|
2013-10-08 01:38:15 +08:00
|
|
|
or_queries = [models.Q(**{orm_lookup: bit})
|
|
|
|
for orm_lookup in orm_lookups]
|
|
|
|
queryset = queryset.filter(reduce(operator.or_, or_queries))
|
2013-08-04 18:18:17 +08:00
|
|
|
if not use_distinct:
|
|
|
|
for search_spec in orm_lookups:
|
|
|
|
if lookup_needs_distinct(self.opts, search_spec):
|
|
|
|
use_distinct = True
|
|
|
|
break
|
|
|
|
|
|
|
|
return queryset, use_distinct
|
|
|
|
|
2013-06-19 03:41:36 +08:00
|
|
|
def get_preserved_filters(self, request):
|
|
|
|
"""
|
|
|
|
Returns the preserved filters querystring.
|
|
|
|
"""
|
2013-07-19 03:17:40 +08:00
|
|
|
match = request.resolver_match
|
2013-06-19 03:41:36 +08:00
|
|
|
if self.preserve_filters and match:
|
|
|
|
opts = self.model._meta
|
2013-07-19 03:17:40 +08:00
|
|
|
current_url = '%s:%s' % (match.app_name, match.url_name)
|
2013-06-19 03:41:36 +08:00
|
|
|
changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name)
|
|
|
|
if current_url == changelist_url:
|
|
|
|
preserved_filters = request.GET.urlencode()
|
|
|
|
else:
|
|
|
|
preserved_filters = request.GET.get('_changelist_filters')
|
|
|
|
|
|
|
|
if preserved_filters:
|
|
|
|
return urlencode({'_changelist_filters': preserved_filters})
|
|
|
|
return ''
|
|
|
|
|
2015-12-27 02:51:22 +08:00
|
|
|
@translation_override(None)
|
2015-03-17 05:55:44 +08:00
|
|
|
def construct_change_message(self, request, form, formsets, add=False):
|
2008-08-10 00:45:15 +08:00
|
|
|
"""
|
2015-12-27 02:51:22 +08:00
|
|
|
Construct a JSON structure describing changes from a changed object.
|
|
|
|
Translations are deactivated so that strings are stored untranslated.
|
|
|
|
Translation happens later on LogEntry access.
|
2008-08-10 00:45:15 +08:00
|
|
|
"""
|
|
|
|
change_message = []
|
2015-03-17 05:55:44 +08:00
|
|
|
if add:
|
2015-12-27 02:51:22 +08:00
|
|
|
change_message.append({'added': {}})
|
2015-03-17 05:55:44 +08:00
|
|
|
elif form.changed_data:
|
2015-12-27 02:51:22 +08:00
|
|
|
change_message.append({'changed': {'fields': form.changed_data}})
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-08-10 00:45:15 +08:00
|
|
|
if formsets:
|
|
|
|
for formset in formsets:
|
|
|
|
for added_object in formset.new_objects:
|
2015-12-27 02:51:22 +08:00
|
|
|
change_message.append({
|
|
|
|
'added': {
|
|
|
|
'name': force_text(added_object._meta.verbose_name),
|
|
|
|
'object': force_text(added_object),
|
|
|
|
}
|
|
|
|
})
|
2008-08-10 00:45:15 +08:00
|
|
|
for changed_object, changed_fields in formset.changed_objects:
|
2015-12-27 02:51:22 +08:00
|
|
|
change_message.append({
|
|
|
|
'changed': {
|
|
|
|
'name': force_text(changed_object._meta.verbose_name),
|
|
|
|
'object': force_text(changed_object),
|
|
|
|
'fields': changed_fields,
|
|
|
|
}
|
|
|
|
})
|
2008-08-10 00:45:15 +08:00
|
|
|
for deleted_object in formset.deleted_objects:
|
2015-12-27 02:51:22 +08:00
|
|
|
change_message.append({
|
|
|
|
'deleted': {
|
|
|
|
'name': force_text(deleted_object._meta.verbose_name),
|
|
|
|
'object': force_text(deleted_object),
|
|
|
|
}
|
|
|
|
})
|
|
|
|
return change_message
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2012-11-18 05:53:31 +08:00
|
|
|
def message_user(self, request, message, level=messages.INFO, extra_tags='',
|
|
|
|
fail_silently=False):
|
2008-08-10 00:45:15 +08:00
|
|
|
"""
|
2009-01-15 04:22:25 +08:00
|
|
|
Send a message to the user. The default implementation
|
2009-12-10 00:57:23 +08:00
|
|
|
posts a message using the django.contrib.messages backend.
|
2012-11-18 05:53:31 +08:00
|
|
|
|
|
|
|
Exposes almost the same API as messages.add_message(), but accepts the
|
|
|
|
positional arguments in a different order to maintain backwards
|
|
|
|
compatibility. For convenience, it accepts the `level` argument as
|
2012-11-29 07:28:30 +08:00
|
|
|
a string rather than the usual level number.
|
2008-08-10 00:45:15 +08:00
|
|
|
"""
|
2012-11-18 05:53:31 +08:00
|
|
|
|
|
|
|
if not isinstance(level, int):
|
|
|
|
# attempt to get the level if passed a string
|
|
|
|
try:
|
|
|
|
level = getattr(messages.constants, level.upper())
|
|
|
|
except AttributeError:
|
|
|
|
levels = messages.constants.DEFAULT_TAGS.values()
|
|
|
|
levels_repr = ', '.join('`%s`' % l for l in levels)
|
|
|
|
raise ValueError('Bad message level string: `%s`. '
|
|
|
|
'Possible values are: %s' % (level, levels_repr))
|
|
|
|
|
|
|
|
messages.add_message(request, level, message, extra_tags=extra_tags,
|
|
|
|
fail_silently=fail_silently)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2010-01-12 10:29:45 +08:00
|
|
|
def save_form(self, request, form, change):
|
2008-08-10 01:12:48 +08:00
|
|
|
"""
|
2008-08-10 04:52:40 +08:00
|
|
|
Given a ModelForm return an unsaved instance. ``change`` is True if
|
|
|
|
the object is being changed, and False if it's being added.
|
2008-08-10 01:12:48 +08:00
|
|
|
"""
|
2010-01-12 10:29:45 +08:00
|
|
|
return form.save(commit=False)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-08-12 01:20:47 +08:00
|
|
|
def save_model(self, request, obj, form, change):
|
|
|
|
"""
|
|
|
|
Given a model instance save it to the database.
|
|
|
|
"""
|
|
|
|
obj.save()
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2011-03-03 08:24:41 +08:00
|
|
|
def delete_model(self, request, obj):
|
2010-11-22 03:00:40 +08:00
|
|
|
"""
|
|
|
|
Given a model instance delete it from the database.
|
|
|
|
"""
|
|
|
|
obj.delete()
|
|
|
|
|
2008-08-10 01:12:48 +08:00
|
|
|
def save_formset(self, request, form, formset, change):
|
|
|
|
"""
|
2008-08-12 01:20:47 +08:00
|
|
|
Given an inline formset save it to the database.
|
2008-08-10 01:12:48 +08:00
|
|
|
"""
|
2008-08-12 01:20:47 +08:00
|
|
|
formset.save()
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2011-07-04 01:56:43 +08:00
|
|
|
def save_related(self, request, form, formsets, change):
|
|
|
|
"""
|
|
|
|
Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
|
|
|
|
list of inline formsets and a boolean value based on whether the
|
|
|
|
parent is being added or changed, save the related objects to the
|
|
|
|
database. Note that at this point save_form() and save_model() have
|
|
|
|
already been called.
|
|
|
|
"""
|
|
|
|
form.save_m2m()
|
|
|
|
for formset in formsets:
|
|
|
|
self.save_formset(request, form, formset, change=change)
|
|
|
|
|
2008-08-10 04:52:40 +08:00
|
|
|
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
|
|
|
|
opts = self.model._meta
|
|
|
|
app_label = opts.app_label
|
2013-06-19 03:41:36 +08:00
|
|
|
preserved_filters = self.get_preserved_filters(request)
|
|
|
|
form_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, form_url)
|
2013-10-24 23:28:09 +08:00
|
|
|
view_on_site_url = self.get_view_on_site_url(obj)
|
2008-08-10 04:52:40 +08:00
|
|
|
context.update({
|
|
|
|
'add': add,
|
|
|
|
'change': change,
|
|
|
|
'has_add_permission': self.has_add_permission(request),
|
|
|
|
'has_change_permission': self.has_change_permission(request, obj),
|
|
|
|
'has_delete_permission': self.has_delete_permission(request, obj),
|
2013-06-23 09:48:09 +08:00
|
|
|
'has_file_field': True, # FIXME - this should check if form or formsets have a FileField,
|
2013-10-24 23:28:09 +08:00
|
|
|
'has_absolute_url': view_on_site_url is not None,
|
|
|
|
'absolute_url': view_on_site_url,
|
2012-07-03 07:33:44 +08:00
|
|
|
'form_url': form_url,
|
2008-08-10 04:52:40 +08:00
|
|
|
'opts': opts,
|
2014-02-02 02:30:54 +08:00
|
|
|
'content_type_id': get_content_type_for_model(self.model).pk,
|
2008-08-10 04:52:40 +08:00
|
|
|
'save_as': self.save_as,
|
|
|
|
'save_on_top': self.save_on_top,
|
2013-09-08 00:52:14 +08:00
|
|
|
'to_field_var': TO_FIELD_VAR,
|
2014-02-10 00:39:04 +08:00
|
|
|
'is_popup_var': IS_POPUP_VAR,
|
|
|
|
'app_label': app_label,
|
2008-08-10 04:52:40 +08:00
|
|
|
})
|
2010-01-13 07:34:03 +08:00
|
|
|
if add and self.add_form_template is not None:
|
|
|
|
form_template = self.add_form_template
|
|
|
|
else:
|
|
|
|
form_template = self.change_form_template
|
2011-04-23 02:17:16 +08:00
|
|
|
|
2014-12-15 00:48:51 +08:00
|
|
|
request.current_app = self.admin_site.name
|
|
|
|
|
2011-04-23 02:17:16 +08:00
|
|
|
return TemplateResponse(request, form_template or [
|
2013-02-05 17:16:07 +08:00
|
|
|
"admin/%s/%s/change_form.html" % (app_label, opts.model_name),
|
2008-08-10 04:52:40 +08:00
|
|
|
"admin/%s/change_form.html" % app_label,
|
|
|
|
"admin/change_form.html"
|
2014-12-15 00:48:51 +08:00
|
|
|
], context)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2012-12-23 03:00:08 +08:00
|
|
|
def response_add(self, request, obj, post_url_continue=None):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
2008-08-10 04:52:40 +08:00
|
|
|
Determines the HttpResponse for the add_view stage.
|
2012-12-23 03:00:08 +08:00
|
|
|
"""
|
2008-08-10 04:52:40 +08:00
|
|
|
opts = obj._meta
|
2012-12-23 03:00:08 +08:00
|
|
|
pk_value = obj._get_pk_val()
|
2013-06-19 03:41:36 +08:00
|
|
|
preserved_filters = self.get_preserved_filters(request)
|
2015-09-07 17:51:03 +08:00
|
|
|
obj_url = reverse(
|
|
|
|
'admin:%s_%s_change' % (opts.app_label, opts.model_name),
|
|
|
|
args=(quote(pk_value),),
|
|
|
|
current_app=self.admin_site.name,
|
|
|
|
)
|
|
|
|
# Add a link to the object's change form if the user can edit the obj.
|
|
|
|
if self.has_change_permission(request, obj):
|
|
|
|
obj_repr = format_html('<a href="{}">{}</a>', urlquote(obj_url), obj)
|
|
|
|
else:
|
|
|
|
obj_repr = force_text(obj)
|
|
|
|
msg_dict = {
|
|
|
|
'name': force_text(opts.verbose_name),
|
|
|
|
'obj': obj_repr,
|
|
|
|
}
|
2008-07-19 07:54:34 +08:00
|
|
|
# Here, we distinguish between different save types by checking for
|
|
|
|
# the presence of keys in request.POST.
|
2013-09-08 00:52:14 +08:00
|
|
|
|
2013-06-20 04:09:40 +08:00
|
|
|
if IS_POPUP_VAR in request.POST:
|
2013-09-08 00:52:14 +08:00
|
|
|
to_field = request.POST.get(TO_FIELD_VAR)
|
|
|
|
if to_field:
|
|
|
|
attr = str(to_field)
|
|
|
|
else:
|
|
|
|
attr = obj._meta.pk.attname
|
|
|
|
value = obj.serializable_value(attr)
|
2015-11-23 18:46:19 +08:00
|
|
|
popup_response_data = json.dumps({
|
2016-01-08 23:21:27 +08:00
|
|
|
'value': six.text_type(value),
|
2015-11-23 18:46:19 +08:00
|
|
|
'obj': six.text_type(obj),
|
|
|
|
})
|
|
|
|
return SimpleTemplateResponse('admin/popup_response.html', {
|
|
|
|
'popup_response_data': popup_response_data,
|
2013-02-26 11:27:52 +08:00
|
|
|
})
|
2013-06-19 03:41:36 +08:00
|
|
|
|
|
|
|
elif "_continue" in request.POST:
|
2015-09-07 17:51:03 +08:00
|
|
|
msg = format_html(
|
|
|
|
_('The {name} "{obj}" was added successfully. You may edit it again below.'),
|
|
|
|
**msg_dict
|
|
|
|
)
|
2013-04-08 19:54:03 +08:00
|
|
|
self.message_user(request, msg, messages.SUCCESS)
|
2012-12-23 03:00:08 +08:00
|
|
|
if post_url_continue is None:
|
2015-09-07 17:51:03 +08:00
|
|
|
post_url_continue = obj_url
|
2014-09-04 20:15:09 +08:00
|
|
|
post_url_continue = add_preserved_filters(
|
|
|
|
{'preserved_filters': preserved_filters, 'opts': opts},
|
|
|
|
post_url_continue
|
|
|
|
)
|
2012-12-23 03:00:08 +08:00
|
|
|
return HttpResponseRedirect(post_url_continue)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2010-10-29 12:24:53 +08:00
|
|
|
elif "_addanother" in request.POST:
|
2015-09-07 17:51:03 +08:00
|
|
|
msg = format_html(
|
|
|
|
_('The {name} "{obj}" was added successfully. You may add another {name} below.'),
|
|
|
|
**msg_dict
|
|
|
|
)
|
2013-04-08 19:54:03 +08:00
|
|
|
self.message_user(request, msg, messages.SUCCESS)
|
2013-06-19 03:41:36 +08:00
|
|
|
redirect_url = request.path
|
|
|
|
redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
|
|
|
|
return HttpResponseRedirect(redirect_url)
|
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
else:
|
2015-09-07 17:51:03 +08:00
|
|
|
msg = format_html(
|
|
|
|
_('The {name} "{obj}" was added successfully.'),
|
|
|
|
**msg_dict
|
|
|
|
)
|
2013-04-08 19:54:03 +08:00
|
|
|
self.message_user(request, msg, messages.SUCCESS)
|
2012-12-31 13:33:21 +08:00
|
|
|
return self.response_post_save_add(request, obj)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2012-12-23 03:00:08 +08:00
|
|
|
def response_change(self, request, obj):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
2008-08-10 04:52:40 +08:00
|
|
|
Determines the HttpResponse for the change_view stage.
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
2013-09-08 00:52:14 +08:00
|
|
|
|
2013-11-18 06:26:20 +08:00
|
|
|
if IS_POPUP_VAR in request.POST:
|
|
|
|
to_field = request.POST.get(TO_FIELD_VAR)
|
|
|
|
attr = str(to_field) if to_field else obj._meta.pk.attname
|
|
|
|
# Retrieve the `object_id` from the resolved pattern arguments.
|
|
|
|
value = request.resolver_match.args[0]
|
|
|
|
new_value = obj.serializable_value(attr)
|
2015-11-23 18:46:19 +08:00
|
|
|
popup_response_data = json.dumps({
|
2013-11-18 06:26:20 +08:00
|
|
|
'action': 'change',
|
2016-01-07 17:07:15 +08:00
|
|
|
'value': six.text_type(value),
|
2015-11-23 18:46:19 +08:00
|
|
|
'obj': six.text_type(obj),
|
2016-01-07 17:07:15 +08:00
|
|
|
'new_value': six.text_type(new_value),
|
2015-11-23 18:46:19 +08:00
|
|
|
})
|
|
|
|
return SimpleTemplateResponse('admin/popup_response.html', {
|
|
|
|
'popup_response_data': popup_response_data,
|
2013-11-18 06:26:20 +08:00
|
|
|
})
|
|
|
|
|
2012-12-23 03:00:08 +08:00
|
|
|
opts = self.model._meta
|
|
|
|
pk_value = obj._get_pk_val()
|
2013-06-19 03:41:36 +08:00
|
|
|
preserved_filters = self.get_preserved_filters(request)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2015-09-07 17:51:03 +08:00
|
|
|
msg_dict = {
|
|
|
|
'name': force_text(opts.verbose_name),
|
|
|
|
'obj': format_html('<a href="{}">{}</a>', urlquote(request.path), obj),
|
|
|
|
}
|
2010-10-29 12:24:53 +08:00
|
|
|
if "_continue" in request.POST:
|
2015-09-07 17:51:03 +08:00
|
|
|
msg = format_html(
|
|
|
|
_('The {name} "{obj}" was changed successfully. You may edit it again below.'),
|
|
|
|
**msg_dict
|
|
|
|
)
|
2013-04-08 19:54:03 +08:00
|
|
|
self.message_user(request, msg, messages.SUCCESS)
|
2013-06-19 03:41:36 +08:00
|
|
|
redirect_url = request.path
|
|
|
|
redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
|
|
|
|
return HttpResponseRedirect(redirect_url)
|
|
|
|
|
2010-10-29 12:24:53 +08:00
|
|
|
elif "_saveasnew" in request.POST:
|
2015-09-07 17:51:03 +08:00
|
|
|
msg = format_html(
|
|
|
|
_('The {name} "{obj}" was added successfully. You may edit it again below.'),
|
|
|
|
**msg_dict
|
|
|
|
)
|
2013-04-08 19:54:03 +08:00
|
|
|
self.message_user(request, msg, messages.SUCCESS)
|
2013-06-19 03:41:36 +08:00
|
|
|
redirect_url = reverse('admin:%s_%s_change' %
|
|
|
|
(opts.app_label, opts.model_name),
|
|
|
|
args=(pk_value,),
|
|
|
|
current_app=self.admin_site.name)
|
|
|
|
redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
|
|
|
|
return HttpResponseRedirect(redirect_url)
|
|
|
|
|
2010-10-29 12:24:53 +08:00
|
|
|
elif "_addanother" in request.POST:
|
2015-09-07 17:51:03 +08:00
|
|
|
msg = format_html(
|
|
|
|
_('The {name} "{obj}" was changed successfully. You may add another {name} below.'),
|
|
|
|
**msg_dict
|
|
|
|
)
|
2013-04-08 19:54:03 +08:00
|
|
|
self.message_user(request, msg, messages.SUCCESS)
|
2013-06-19 03:41:36 +08:00
|
|
|
redirect_url = reverse('admin:%s_%s_add' %
|
|
|
|
(opts.app_label, opts.model_name),
|
|
|
|
current_app=self.admin_site.name)
|
|
|
|
redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
|
|
|
|
return HttpResponseRedirect(redirect_url)
|
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
else:
|
2015-09-07 17:51:03 +08:00
|
|
|
msg = format_html(
|
|
|
|
_('The {name} "{obj}" was changed successfully.'),
|
|
|
|
**msg_dict
|
|
|
|
)
|
2013-04-08 19:54:03 +08:00
|
|
|
self.message_user(request, msg, messages.SUCCESS)
|
2012-12-31 13:33:21 +08:00
|
|
|
return self.response_post_save_change(request, obj)
|
2012-12-23 03:00:08 +08:00
|
|
|
|
2012-12-31 13:33:21 +08:00
|
|
|
def response_post_save_add(self, request, obj):
|
2012-12-23 03:00:08 +08:00
|
|
|
"""
|
2012-12-31 13:33:21 +08:00
|
|
|
Figure out where to redirect after the 'Save' button has been pressed
|
|
|
|
when adding a new object.
|
|
|
|
"""
|
|
|
|
opts = self.model._meta
|
|
|
|
if self.has_change_permission(request, None):
|
|
|
|
post_url = reverse('admin:%s_%s_changelist' %
|
2013-02-05 17:16:07 +08:00
|
|
|
(opts.app_label, opts.model_name),
|
2012-12-31 13:33:21 +08:00
|
|
|
current_app=self.admin_site.name)
|
2013-06-19 03:41:36 +08:00
|
|
|
preserved_filters = self.get_preserved_filters(request)
|
|
|
|
post_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, post_url)
|
2012-12-31 13:33:21 +08:00
|
|
|
else:
|
|
|
|
post_url = reverse('admin:index',
|
|
|
|
current_app=self.admin_site.name)
|
|
|
|
return HttpResponseRedirect(post_url)
|
|
|
|
|
|
|
|
def response_post_save_change(self, request, obj):
|
|
|
|
"""
|
|
|
|
Figure out where to redirect after the 'Save' button has been pressed
|
|
|
|
when editing an existing object.
|
2012-12-23 03:00:08 +08:00
|
|
|
"""
|
|
|
|
opts = self.model._meta
|
2013-06-19 03:41:36 +08:00
|
|
|
|
2012-12-23 03:00:08 +08:00
|
|
|
if self.has_change_permission(request, None):
|
|
|
|
post_url = reverse('admin:%s_%s_changelist' %
|
2013-02-05 17:16:07 +08:00
|
|
|
(opts.app_label, opts.model_name),
|
2012-12-23 03:00:08 +08:00
|
|
|
current_app=self.admin_site.name)
|
2013-06-19 03:41:36 +08:00
|
|
|
preserved_filters = self.get_preserved_filters(request)
|
|
|
|
post_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, post_url)
|
2012-12-23 03:00:08 +08:00
|
|
|
else:
|
|
|
|
post_url = reverse('admin:index',
|
|
|
|
current_app=self.admin_site.name)
|
|
|
|
return HttpResponseRedirect(post_url)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-03-24 04:22:56 +08:00
|
|
|
def response_action(self, request, queryset):
|
|
|
|
"""
|
|
|
|
Handle an admin action. This is called if a request is POSTed to the
|
|
|
|
changelist; it returns an HttpResponse if the action was handled, and
|
|
|
|
None otherwise.
|
|
|
|
"""
|
2010-02-23 22:48:15 +08:00
|
|
|
|
2009-03-24 04:22:56 +08:00
|
|
|
# There can be multiple action forms on the page (at the top
|
|
|
|
# and bottom of the change list, for example). Get the action
|
|
|
|
# whose button was pushed.
|
|
|
|
try:
|
|
|
|
action_index = int(request.POST.get('index', 0))
|
|
|
|
except ValueError:
|
|
|
|
action_index = 0
|
|
|
|
|
|
|
|
# Construct the action form.
|
|
|
|
data = request.POST.copy()
|
|
|
|
data.pop(helpers.ACTION_CHECKBOX_NAME, None)
|
|
|
|
data.pop("index", None)
|
2009-05-06 06:25:35 +08:00
|
|
|
|
2009-04-07 04:23:33 +08:00
|
|
|
# Use the action whose button was pushed
|
|
|
|
try:
|
|
|
|
data.update({'action': data.getlist('action')[action_index]})
|
|
|
|
except IndexError:
|
|
|
|
# If we didn't get an action from the chosen form that's invalid
|
|
|
|
# POST data, so by deleting action it'll fail the validation check
|
|
|
|
# below. So no need to do anything here
|
|
|
|
pass
|
2009-05-06 06:25:35 +08:00
|
|
|
|
2009-03-24 04:22:56 +08:00
|
|
|
action_form = self.action_form(data, auto_id=None)
|
|
|
|
action_form.fields['action'].choices = self.get_action_choices(request)
|
|
|
|
|
|
|
|
# If the form's valid we can handle the action.
|
|
|
|
if action_form.is_valid():
|
|
|
|
action = action_form.cleaned_data['action']
|
2010-01-26 23:03:23 +08:00
|
|
|
select_across = action_form.cleaned_data['select_across']
|
2013-06-23 09:48:09 +08:00
|
|
|
func = self.get_actions(request)[action][0]
|
2009-03-24 16:22:23 +08:00
|
|
|
|
|
|
|
# Get the list of selected PKs. If nothing's selected, we can't
|
2010-01-26 23:03:23 +08:00
|
|
|
# perform an action on it, so bail. Except we want to perform
|
2010-05-03 07:02:16 +08:00
|
|
|
# the action explicitly on all objects.
|
2009-03-24 04:22:56 +08:00
|
|
|
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
|
2010-01-26 23:03:23 +08:00
|
|
|
if not selected and not select_across:
|
2009-12-13 05:51:47 +08:00
|
|
|
# Reminder that something needs to be selected or nothing will happen
|
2010-05-03 07:02:16 +08:00
|
|
|
msg = _("Items must be selected in order to perform "
|
|
|
|
"actions on them. No items have been changed.")
|
2013-04-08 19:54:03 +08:00
|
|
|
self.message_user(request, msg, messages.WARNING)
|
2009-03-24 04:22:56 +08:00
|
|
|
return None
|
|
|
|
|
2010-01-26 23:03:23 +08:00
|
|
|
if not select_across:
|
|
|
|
# Perform the action only on the selected objects
|
|
|
|
queryset = queryset.filter(pk__in=selected)
|
|
|
|
|
|
|
|
response = func(self, request, queryset)
|
2009-03-24 16:22:23 +08:00
|
|
|
|
2013-05-29 22:55:56 +08:00
|
|
|
# Actions may return an HttpResponse-like object, which will be
|
|
|
|
# used as the response from the POST. If not, we'll be a good
|
|
|
|
# little HTTP citizen and redirect back to the changelist page.
|
|
|
|
if isinstance(response, HttpResponseBase):
|
2009-03-24 04:22:56 +08:00
|
|
|
return response
|
|
|
|
else:
|
2010-09-08 04:55:53 +08:00
|
|
|
return HttpResponseRedirect(request.get_full_path())
|
2009-12-13 05:51:47 +08:00
|
|
|
else:
|
2009-12-15 00:01:43 +08:00
|
|
|
msg = _("No action selected.")
|
2013-04-08 19:54:03 +08:00
|
|
|
self.message_user(request, msg, messages.WARNING)
|
2010-05-03 07:02:16 +08:00
|
|
|
return None
|
2009-03-24 04:22:56 +08:00
|
|
|
|
2013-11-18 06:26:20 +08:00
|
|
|
def response_delete(self, request, obj_display, obj_id):
|
2013-09-07 08:05:01 +08:00
|
|
|
"""
|
|
|
|
Determines the HttpResponse for the delete_view stage.
|
|
|
|
"""
|
|
|
|
|
|
|
|
opts = self.model._meta
|
|
|
|
|
2013-11-18 06:26:20 +08:00
|
|
|
if IS_POPUP_VAR in request.POST:
|
2015-11-23 18:46:19 +08:00
|
|
|
popup_response_data = json.dumps({
|
2013-11-18 06:26:20 +08:00
|
|
|
'action': 'delete',
|
2016-01-09 08:39:05 +08:00
|
|
|
'value': str(obj_id),
|
2015-11-23 18:46:19 +08:00
|
|
|
})
|
|
|
|
return SimpleTemplateResponse('admin/popup_response.html', {
|
|
|
|
'popup_response_data': popup_response_data,
|
2013-11-18 06:26:20 +08:00
|
|
|
})
|
|
|
|
|
2013-10-20 07:33:10 +08:00
|
|
|
self.message_user(request,
|
|
|
|
_('The %(name)s "%(obj)s" was deleted successfully.') % {
|
2013-10-18 06:27:45 +08:00
|
|
|
'name': force_text(opts.verbose_name),
|
2013-11-18 06:26:20 +08:00
|
|
|
'obj': force_text(obj_display),
|
2013-10-20 07:33:10 +08:00
|
|
|
}, messages.SUCCESS)
|
2013-09-07 08:05:01 +08:00
|
|
|
|
|
|
|
if self.has_change_permission(request, None):
|
|
|
|
post_url = reverse('admin:%s_%s_changelist' %
|
|
|
|
(opts.app_label, opts.model_name),
|
|
|
|
current_app=self.admin_site.name)
|
|
|
|
preserved_filters = self.get_preserved_filters(request)
|
|
|
|
post_url = add_preserved_filters(
|
|
|
|
{'preserved_filters': preserved_filters, 'opts': opts}, post_url
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
post_url = reverse('admin:index',
|
|
|
|
current_app=self.admin_site.name)
|
|
|
|
return HttpResponseRedirect(post_url)
|
|
|
|
|
|
|
|
def render_delete_form(self, request, context):
|
|
|
|
opts = self.model._meta
|
|
|
|
app_label = opts.app_label
|
|
|
|
|
2014-12-15 00:48:51 +08:00
|
|
|
request.current_app = self.admin_site.name
|
2013-11-18 06:26:20 +08:00
|
|
|
context.update(
|
|
|
|
to_field_var=TO_FIELD_VAR,
|
|
|
|
is_popup_var=IS_POPUP_VAR,
|
2015-11-23 18:46:19 +08:00
|
|
|
media=self.media,
|
2013-11-18 06:26:20 +08:00
|
|
|
)
|
2014-12-15 00:48:51 +08:00
|
|
|
|
2013-09-07 08:05:01 +08:00
|
|
|
return TemplateResponse(request,
|
|
|
|
self.delete_confirmation_template or [
|
2013-10-18 06:27:45 +08:00
|
|
|
"admin/{}/{}/delete_confirmation.html".format(app_label, opts.model_name),
|
|
|
|
"admin/{}/delete_confirmation.html".format(app_label),
|
|
|
|
"admin/delete_confirmation.html"
|
2014-12-15 00:48:51 +08:00
|
|
|
], context)
|
2013-09-07 08:05:01 +08:00
|
|
|
|
2014-02-10 00:39:04 +08:00
|
|
|
def get_inline_formsets(self, request, formsets, inline_instances,
|
|
|
|
obj=None):
|
2008-07-19 07:54:34 +08:00
|
|
|
inline_admin_formsets = []
|
2011-10-07 08:41:25 +08:00
|
|
|
for inline, formset in zip(inline_instances, formsets):
|
2014-02-10 00:39:04 +08:00
|
|
|
fieldsets = list(inline.get_fieldsets(request, obj))
|
|
|
|
readonly = list(inline.get_readonly_fields(request, obj))
|
|
|
|
prepopulated = dict(inline.get_prepopulated_fields(request, obj))
|
2009-12-23 02:29:00 +08:00
|
|
|
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
|
2011-04-22 20:02:25 +08:00
|
|
|
fieldsets, prepopulated, readonly, model_admin=self)
|
2008-07-19 07:54:34 +08:00
|
|
|
inline_admin_formsets.append(inline_admin_formset)
|
2014-02-10 00:39:04 +08:00
|
|
|
return inline_admin_formsets
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2014-02-27 06:34:19 +08:00
|
|
|
def get_changeform_initial_data(self, request):
|
|
|
|
"""
|
|
|
|
Get the initial form data.
|
|
|
|
Unless overridden, this populates from the GET params.
|
|
|
|
"""
|
|
|
|
initial = dict(request.GET.items())
|
|
|
|
for k in initial:
|
|
|
|
try:
|
|
|
|
f = self.model._meta.get_field(k)
|
2015-01-02 23:14:23 +08:00
|
|
|
except FieldDoesNotExist:
|
2014-02-27 06:34:19 +08:00
|
|
|
continue
|
|
|
|
# We have to special-case M2Ms as a list of comma-separated PKs.
|
2016-03-11 01:21:25 +08:00
|
|
|
if f.many_to_many:
|
2014-02-27 06:34:19 +08:00
|
|
|
initial[k] = initial[k].split(",")
|
|
|
|
return initial
|
|
|
|
|
2010-02-09 23:02:39 +08:00
|
|
|
@csrf_protect_m
|
2013-03-12 02:58:08 +08:00
|
|
|
@transaction.atomic
|
2014-02-10 00:39:04 +08:00
|
|
|
def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
|
|
|
|
|
2014-08-07 12:18:10 +08:00
|
|
|
to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))
|
|
|
|
if to_field and not self.to_field_allowed(request, to_field):
|
|
|
|
raise DisallowedModelAdminToField("The field %s cannot be referenced." % to_field)
|
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
model = self.model
|
|
|
|
opts = model._meta
|
2016-01-24 21:13:23 +08:00
|
|
|
|
|
|
|
if request.method == 'POST' and '_saveasnew' in request.POST:
|
|
|
|
object_id = None
|
|
|
|
|
2014-02-10 00:39:04 +08:00
|
|
|
add = object_id is None
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2014-02-10 00:39:04 +08:00
|
|
|
if add:
|
|
|
|
if not self.has_add_permission(request):
|
|
|
|
raise PermissionDenied
|
|
|
|
obj = None
|
|
|
|
|
|
|
|
else:
|
2013-11-18 06:26:20 +08:00
|
|
|
obj = self.get_object(request, unquote(object_id), to_field)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2014-02-10 00:39:04 +08:00
|
|
|
if not self.has_change_permission(request, obj):
|
|
|
|
raise PermissionDenied
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2014-02-10 00:39:04 +08:00
|
|
|
if obj is None:
|
|
|
|
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
|
|
|
|
'name': force_text(opts.verbose_name), 'key': escape(object_id)})
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
ModelForm = self.get_form(request, obj)
|
|
|
|
if request.method == 'POST':
|
|
|
|
form = ModelForm(request.POST, request.FILES, instance=obj)
|
2008-08-10 04:52:40 +08:00
|
|
|
if form.is_valid():
|
|
|
|
form_validated = True
|
2014-02-10 00:39:04 +08:00
|
|
|
new_object = self.save_form(request, form, change=not add)
|
2008-08-10 04:52:40 +08:00
|
|
|
else:
|
|
|
|
form_validated = False
|
2013-11-15 10:26:19 +08:00
|
|
|
new_object = form.instance
|
2014-11-28 02:34:14 +08:00
|
|
|
formsets, inline_instances = self._create_formsets(request, new_object, change=not add)
|
2008-08-10 04:52:40 +08:00
|
|
|
if all_valid(formsets) and form_validated:
|
2014-02-10 00:39:04 +08:00
|
|
|
self.save_model(request, new_object, form, not add)
|
|
|
|
self.save_related(request, form, formsets, not add)
|
2015-03-17 05:55:44 +08:00
|
|
|
change_message = self.construct_change_message(request, form, formsets, add)
|
2014-02-10 00:39:04 +08:00
|
|
|
if add:
|
2015-03-17 05:55:44 +08:00
|
|
|
self.log_addition(request, new_object, change_message)
|
2014-02-10 00:39:04 +08:00
|
|
|
return self.response_add(request, new_object)
|
|
|
|
else:
|
|
|
|
self.log_change(request, new_object, change_message)
|
|
|
|
return self.response_change(request, new_object)
|
2015-04-25 09:31:26 +08:00
|
|
|
else:
|
|
|
|
form_validated = False
|
2008-07-19 07:54:34 +08:00
|
|
|
else:
|
2014-02-10 00:39:04 +08:00
|
|
|
if add:
|
2014-02-27 06:34:19 +08:00
|
|
|
initial = self.get_changeform_initial_data(request)
|
2014-02-10 00:39:04 +08:00
|
|
|
form = ModelForm(initial=initial)
|
2015-03-23 04:32:46 +08:00
|
|
|
formsets, inline_instances = self._create_formsets(request, form.instance, change=False)
|
2014-02-10 00:39:04 +08:00
|
|
|
else:
|
|
|
|
form = ModelForm(instance=obj)
|
2014-11-28 02:34:14 +08:00
|
|
|
formsets, inline_instances = self._create_formsets(request, obj, change=True)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2014-02-10 00:39:04 +08:00
|
|
|
adminForm = helpers.AdminForm(
|
|
|
|
form,
|
|
|
|
list(self.get_fieldsets(request, obj)),
|
2011-04-22 20:02:25 +08:00
|
|
|
self.get_prepopulated_fields(request, obj),
|
|
|
|
self.get_readonly_fields(request, obj),
|
2009-12-23 02:29:00 +08:00
|
|
|
model_admin=self)
|
2008-07-19 07:54:34 +08:00
|
|
|
media = self.media + adminForm.media
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2014-02-10 00:39:04 +08:00
|
|
|
inline_formsets = self.get_inline_formsets(request, formsets, inline_instances, obj)
|
|
|
|
for inline_formset in inline_formsets:
|
|
|
|
media = media + inline_formset.media
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2015-01-01 05:25:00 +08:00
|
|
|
context = dict(self.admin_site.each_context(request),
|
2014-02-10 00:39:04 +08:00
|
|
|
title=(_('Add %s') if add else _('Change %s')) % force_text(opts.verbose_name),
|
2013-09-07 01:31:44 +08:00
|
|
|
adminform=adminForm,
|
|
|
|
object_id=object_id,
|
|
|
|
original=obj,
|
2013-10-16 04:36:49 +08:00
|
|
|
is_popup=(IS_POPUP_VAR in request.POST or
|
|
|
|
IS_POPUP_VAR in request.GET),
|
2014-08-07 12:18:10 +08:00
|
|
|
to_field=to_field,
|
2013-09-07 01:31:44 +08:00
|
|
|
media=media,
|
2014-02-10 00:39:04 +08:00
|
|
|
inline_admin_formsets=inline_formsets,
|
2013-09-07 01:31:44 +08:00
|
|
|
errors=helpers.AdminErrorList(form, formsets),
|
|
|
|
preserved_filters=self.get_preserved_filters(request),
|
|
|
|
)
|
2014-02-10 00:39:04 +08:00
|
|
|
|
2015-04-25 09:31:26 +08:00
|
|
|
# Hide the "Save" and "Save and continue" buttons if "Save as New" was
|
|
|
|
# previously chosen to prevent the interface from getting confusing.
|
|
|
|
if request.method == 'POST' and not form_validated and "_saveasnew" in request.POST:
|
|
|
|
context['show_save'] = False
|
|
|
|
context['show_save_and_continue'] = False
|
2016-01-24 21:13:23 +08:00
|
|
|
# Use the change template instead of the add template.
|
|
|
|
add = False
|
2015-04-25 09:31:26 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
context.update(extra_context or {})
|
2014-02-10 00:39:04 +08:00
|
|
|
|
|
|
|
return self.render_change_form(request, context, add=add, change=not add, obj=obj, form_url=form_url)
|
|
|
|
|
|
|
|
def add_view(self, request, form_url='', extra_context=None):
|
|
|
|
return self.changeform_view(request, None, form_url, extra_context)
|
|
|
|
|
|
|
|
def change_view(self, request, object_id, form_url='', extra_context=None):
|
|
|
|
return self.changeform_view(request, object_id, form_url, extra_context)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2010-02-09 23:02:39 +08:00
|
|
|
@csrf_protect_m
|
2008-07-19 07:54:34 +08:00
|
|
|
def changelist_view(self, request, extra_context=None):
|
2011-10-26 20:19:18 +08:00
|
|
|
"""
|
|
|
|
The 'change list' admin view for this model.
|
|
|
|
"""
|
2009-12-18 18:08:05 +08:00
|
|
|
from django.contrib.admin.views.main import ERROR_FLAG
|
2008-07-19 07:54:34 +08:00
|
|
|
opts = self.model._meta
|
|
|
|
app_label = opts.app_label
|
|
|
|
if not self.has_change_permission(request, None):
|
|
|
|
raise PermissionDenied
|
2009-05-06 06:25:35 +08:00
|
|
|
|
2011-10-26 17:37:07 +08:00
|
|
|
list_display = self.get_list_display(request)
|
2011-10-26 20:19:18 +08:00
|
|
|
list_display_links = self.get_list_display_links(request, list_display)
|
2012-11-26 03:39:23 +08:00
|
|
|
list_filter = self.get_list_filter(request)
|
2013-08-04 00:15:15 +08:00
|
|
|
search_fields = self.get_search_fields(request)
|
2015-03-16 18:00:16 +08:00
|
|
|
list_select_related = self.get_list_select_related(request)
|
2011-10-26 17:37:07 +08:00
|
|
|
|
2011-10-26 20:19:18 +08:00
|
|
|
# Check actions to see if any are available on this changelist
|
|
|
|
actions = self.get_actions(request)
|
2011-10-26 17:37:07 +08:00
|
|
|
if actions:
|
|
|
|
# Add the action checkboxes if there are any actions available.
|
2013-06-23 09:48:09 +08:00
|
|
|
list_display = ['action_checkbox'] + list(list_display)
|
2009-05-06 06:25:35 +08:00
|
|
|
|
2009-12-18 18:08:05 +08:00
|
|
|
ChangeList = self.get_changelist(request)
|
2008-07-19 07:54:34 +08:00
|
|
|
try:
|
2011-10-26 17:37:07 +08:00
|
|
|
cl = ChangeList(request, self.model, list_display,
|
2012-11-26 03:39:23 +08:00
|
|
|
list_display_links, list_filter, self.date_hierarchy,
|
2015-03-16 18:00:16 +08:00
|
|
|
search_fields, list_select_related, self.list_per_page,
|
2013-08-04 00:15:15 +08:00
|
|
|
self.list_max_show_all, self.list_editable, self)
|
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
except IncorrectLookupParameters:
|
|
|
|
# Wacky lookup parameters were given, so redirect to the main
|
|
|
|
# changelist page, without parameters, and pass an 'invalid=1'
|
2010-05-03 07:02:16 +08:00
|
|
|
# parameter via the query string. If wacky parameters were given
|
|
|
|
# and the 'invalid=1' parameter was already in the query string,
|
|
|
|
# something is screwed up with the database, so display an error
|
|
|
|
# page.
|
2008-07-19 07:54:34 +08:00
|
|
|
if ERROR_FLAG in request.GET.keys():
|
2011-04-23 02:17:16 +08:00
|
|
|
return SimpleTemplateResponse('admin/invalid_setup.html', {
|
|
|
|
'title': _('Database error'),
|
|
|
|
})
|
2008-07-19 07:54:34 +08:00
|
|
|
return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')
|
2009-05-06 06:25:35 +08:00
|
|
|
|
2010-05-03 07:02:16 +08:00
|
|
|
# If the request was POSTed, this might be a bulk action or a bulk
|
|
|
|
# edit. Try to look up an action or confirmation first, but if this
|
|
|
|
# isn't an action the POST will fall through to the bulk edit check,
|
|
|
|
# below.
|
|
|
|
action_failed = False
|
|
|
|
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
|
|
|
|
|
|
|
|
# Actions with no confirmation
|
|
|
|
if (actions and request.method == 'POST' and
|
|
|
|
'index' in request.POST and '_save' not in request.POST):
|
|
|
|
if selected:
|
2013-03-08 22:15:23 +08:00
|
|
|
response = self.response_action(request, queryset=cl.get_queryset(request))
|
2010-05-03 07:02:16 +08:00
|
|
|
if response:
|
|
|
|
return response
|
|
|
|
else:
|
|
|
|
action_failed = True
|
|
|
|
else:
|
|
|
|
msg = _("Items must be selected in order to perform "
|
|
|
|
"actions on them. No items have been changed.")
|
2013-04-08 19:54:03 +08:00
|
|
|
self.message_user(request, msg, messages.WARNING)
|
2010-05-03 07:02:16 +08:00
|
|
|
action_failed = True
|
|
|
|
|
|
|
|
# Actions with confirmation
|
|
|
|
if (actions and request.method == 'POST' and
|
|
|
|
helpers.ACTION_CHECKBOX_NAME in request.POST and
|
|
|
|
'index' not in request.POST and '_save' not in request.POST):
|
|
|
|
if selected:
|
2013-03-08 22:15:23 +08:00
|
|
|
response = self.response_action(request, queryset=cl.get_queryset(request))
|
2010-05-03 07:02:16 +08:00
|
|
|
if response:
|
|
|
|
return response
|
|
|
|
else:
|
|
|
|
action_failed = True
|
2009-03-24 16:22:23 +08:00
|
|
|
|
2009-03-18 04:51:47 +08:00
|
|
|
# If we're allowing changelist editing, we need to construct a formset
|
|
|
|
# for the changelist given all the fields to be edited. Then we'll
|
|
|
|
# use the formset to validate/process POSTed data.
|
|
|
|
formset = cl.formset = None
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-03-18 04:51:47 +08:00
|
|
|
# Handle POSTed bulk-edit data.
|
2011-01-02 09:32:40 +08:00
|
|
|
if (request.method == "POST" and cl.list_editable and
|
2010-05-03 07:02:16 +08:00
|
|
|
'_save' in request.POST and not action_failed):
|
2009-03-18 04:51:47 +08:00
|
|
|
FormSet = self.get_changelist_formset(request)
|
2015-11-20 00:13:39 +08:00
|
|
|
formset = cl.formset = FormSet(request.POST, request.FILES, queryset=self.get_queryset(request))
|
2009-03-18 04:51:47 +08:00
|
|
|
if formset.is_valid():
|
|
|
|
changecount = 0
|
|
|
|
for form in formset.forms:
|
|
|
|
if form.has_changed():
|
|
|
|
obj = self.save_form(request, form, change=True)
|
|
|
|
self.save_model(request, obj, form, change=True)
|
2011-08-12 22:14:24 +08:00
|
|
|
self.save_related(request, form, formsets=[], change=True)
|
2009-03-18 04:51:47 +08:00
|
|
|
change_msg = self.construct_change_message(request, form, None)
|
|
|
|
self.log_change(request, obj, change_msg)
|
|
|
|
changecount += 1
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-03-18 04:51:47 +08:00
|
|
|
if changecount:
|
2009-03-18 17:19:24 +08:00
|
|
|
if changecount == 1:
|
2012-07-21 16:00:10 +08:00
|
|
|
name = force_text(opts.verbose_name)
|
2009-03-18 17:19:24 +08:00
|
|
|
else:
|
2012-07-21 16:00:10 +08:00
|
|
|
name = force_text(opts.verbose_name_plural)
|
2009-05-06 06:25:35 +08:00
|
|
|
msg = ungettext("%(count)s %(name)s was changed successfully.",
|
|
|
|
"%(count)s %(name)s were changed successfully.",
|
|
|
|
changecount) % {'count': changecount,
|
|
|
|
'name': name,
|
2012-07-21 16:00:10 +08:00
|
|
|
'obj': force_text(obj)}
|
2013-04-08 19:54:03 +08:00
|
|
|
self.message_user(request, msg, messages.SUCCESS)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-03-18 04:51:47 +08:00
|
|
|
return HttpResponseRedirect(request.get_full_path())
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-03-18 04:51:47 +08:00
|
|
|
# Handle GET -- construct a formset for display.
|
2011-01-02 09:32:40 +08:00
|
|
|
elif cl.list_editable:
|
2009-03-18 04:51:47 +08:00
|
|
|
FormSet = self.get_changelist_formset(request)
|
|
|
|
formset = cl.formset = FormSet(queryset=cl.result_list)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2009-03-18 04:51:47 +08:00
|
|
|
# Build the list of media to be used by the formset.
|
|
|
|
if formset:
|
|
|
|
media = self.media + formset.media
|
|
|
|
else:
|
2009-03-24 04:22:56 +08:00
|
|
|
media = self.media
|
2009-03-24 16:22:23 +08:00
|
|
|
|
2009-03-24 04:22:56 +08:00
|
|
|
# Build the action form and populate it with available actions.
|
2009-04-07 04:23:33 +08:00
|
|
|
if actions:
|
|
|
|
action_form = self.action_form(auto_id=None)
|
|
|
|
action_form.fields['action'].choices = self.get_action_choices(request)
|
|
|
|
else:
|
|
|
|
action_form = None
|
2009-03-18 04:51:47 +08:00
|
|
|
|
2010-03-01 22:34:07 +08:00
|
|
|
selection_note_all = ungettext('%(total_count)s selected',
|
|
|
|
'All %(total_count)s selected', cl.result_count)
|
2010-01-06 02:24:27 +08:00
|
|
|
|
2013-12-09 01:20:06 +08:00
|
|
|
context = dict(
|
2015-01-01 05:25:00 +08:00
|
|
|
self.admin_site.each_context(request),
|
2013-09-07 01:31:44 +08:00
|
|
|
module_name=force_text(opts.verbose_name_plural),
|
|
|
|
selection_note=_('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
|
|
|
|
selection_note_all=selection_note_all % {'total_count': cl.result_count},
|
|
|
|
title=cl.title,
|
|
|
|
is_popup=cl.is_popup,
|
2013-09-08 00:52:14 +08:00
|
|
|
to_field=cl.to_field,
|
2013-09-07 01:31:44 +08:00
|
|
|
cl=cl,
|
|
|
|
media=media,
|
|
|
|
has_add_permission=self.has_add_permission(request),
|
|
|
|
opts=cl.opts,
|
|
|
|
action_form=action_form,
|
|
|
|
actions_on_top=self.actions_on_top,
|
|
|
|
actions_on_bottom=self.actions_on_bottom,
|
|
|
|
actions_selection_counter=self.actions_selection_counter,
|
|
|
|
preserved_filters=self.get_preserved_filters(request),
|
|
|
|
)
|
2008-07-19 07:54:34 +08:00
|
|
|
context.update(extra_context or {})
|
2011-04-23 02:17:16 +08:00
|
|
|
|
2014-12-15 00:48:51 +08:00
|
|
|
request.current_app = self.admin_site.name
|
|
|
|
|
2011-04-23 02:17:16 +08:00
|
|
|
return TemplateResponse(request, self.change_list_template or [
|
2013-02-05 17:16:07 +08:00
|
|
|
'admin/%s/%s/change_list.html' % (app_label, opts.model_name),
|
2008-07-19 07:54:34 +08:00
|
|
|
'admin/%s/change_list.html' % app_label,
|
|
|
|
'admin/change_list.html'
|
2014-12-15 00:48:51 +08:00
|
|
|
], context)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2010-02-09 23:02:39 +08:00
|
|
|
@csrf_protect_m
|
2013-03-12 02:58:08 +08:00
|
|
|
@transaction.atomic
|
2008-07-19 07:54:34 +08:00
|
|
|
def delete_view(self, request, object_id, extra_context=None):
|
|
|
|
"The 'delete' admin view for this model."
|
|
|
|
opts = self.model._meta
|
|
|
|
app_label = opts.app_label
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2013-11-18 06:26:20 +08:00
|
|
|
to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))
|
|
|
|
if to_field and not self.to_field_allowed(request, to_field):
|
|
|
|
raise DisallowedModelAdminToField("The field %s cannot be referenced." % to_field)
|
|
|
|
|
|
|
|
obj = self.get_object(request, unquote(object_id), to_field)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
if not self.has_delete_permission(request, obj):
|
|
|
|
raise PermissionDenied
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
if obj is None:
|
2013-06-23 09:48:09 +08:00
|
|
|
raise Http404(
|
|
|
|
_('%(name)s object with primary key %(key)r does not exist.') %
|
2013-10-20 07:33:10 +08:00
|
|
|
{'name': force_text(opts.verbose_name), 'key': escape(object_id)}
|
2013-06-23 09:48:09 +08:00
|
|
|
)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
using = router.db_for_write(self.model)
|
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
# Populate deleted_objects, a data structure of all related objects that
|
|
|
|
# will also be deleted.
|
2014-08-14 19:17:52 +08:00
|
|
|
(deleted_objects, model_count, perms_needed, protected) = get_deleted_objects(
|
2010-11-10 00:46:42 +08:00
|
|
|
[obj], opts, request.user, self.admin_site, using)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2016-03-21 18:50:30 +08:00
|
|
|
if request.POST and not protected: # The user has confirmed the deletion.
|
2008-07-19 07:54:34 +08:00
|
|
|
if perms_needed:
|
|
|
|
raise PermissionDenied
|
2012-07-21 16:00:10 +08:00
|
|
|
obj_display = force_text(obj)
|
2013-11-18 06:26:20 +08:00
|
|
|
attr = str(to_field) if to_field else opts.pk.attname
|
|
|
|
obj_id = obj.serializable_value(attr)
|
2009-05-07 21:10:59 +08:00
|
|
|
self.log_deletion(request, obj, obj_display)
|
2010-11-22 03:00:40 +08:00
|
|
|
self.delete_model(request, obj)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2013-11-18 06:26:20 +08:00
|
|
|
return self.response_delete(request, obj_display, obj_id)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2012-07-21 16:00:10 +08:00
|
|
|
object_name = force_text(opts.verbose_name)
|
2011-01-20 09:00:47 +08:00
|
|
|
|
|
|
|
if perms_needed or protected:
|
|
|
|
title = _("Cannot delete %(name)s") % {"name": object_name}
|
|
|
|
else:
|
|
|
|
title = _("Are you sure?")
|
|
|
|
|
2013-12-09 01:20:06 +08:00
|
|
|
context = dict(
|
2015-01-01 05:25:00 +08:00
|
|
|
self.admin_site.each_context(request),
|
2013-09-07 01:31:44 +08:00
|
|
|
title=title,
|
|
|
|
object_name=object_name,
|
|
|
|
object=obj,
|
|
|
|
deleted_objects=deleted_objects,
|
2015-02-25 20:15:56 +08:00
|
|
|
model_count=dict(model_count).items(),
|
2013-09-07 01:31:44 +08:00
|
|
|
perms_lacking=perms_needed,
|
|
|
|
protected=protected,
|
|
|
|
opts=opts,
|
|
|
|
app_label=app_label,
|
|
|
|
preserved_filters=self.get_preserved_filters(request),
|
2013-11-18 06:26:20 +08:00
|
|
|
is_popup=(IS_POPUP_VAR in request.POST or
|
|
|
|
IS_POPUP_VAR in request.GET),
|
|
|
|
to_field=to_field,
|
2013-09-07 01:31:44 +08:00
|
|
|
)
|
2008-07-19 07:54:34 +08:00
|
|
|
context.update(extra_context or {})
|
2011-04-23 02:17:16 +08:00
|
|
|
|
2013-09-07 08:05:01 +08:00
|
|
|
return self.render_delete_form(request, context)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def history_view(self, request, object_id, extra_context=None):
|
|
|
|
"The 'history' admin view for this model."
|
|
|
|
from django.contrib.admin.models import LogEntry
|
2013-02-05 07:57:59 +08:00
|
|
|
# First check if the user can see this history.
|
2008-07-19 07:54:34 +08:00
|
|
|
model = self.model
|
2015-02-13 02:40:23 +08:00
|
|
|
obj = self.get_object(request, unquote(object_id))
|
|
|
|
if obj is None:
|
|
|
|
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
|
|
|
|
'name': force_text(model._meta.verbose_name),
|
|
|
|
'key': escape(object_id),
|
|
|
|
})
|
2013-02-05 07:57:59 +08:00
|
|
|
|
|
|
|
if not self.has_change_permission(request, obj):
|
|
|
|
raise PermissionDenied
|
|
|
|
|
|
|
|
# Then get the history for this object.
|
2008-07-19 07:54:34 +08:00
|
|
|
opts = model._meta
|
2008-08-26 03:56:14 +08:00
|
|
|
app_label = opts.app_label
|
2008-07-19 07:54:34 +08:00
|
|
|
action_list = LogEntry.objects.filter(
|
2013-02-05 07:57:59 +08:00
|
|
|
object_id=unquote(object_id),
|
2014-02-02 02:30:54 +08:00
|
|
|
content_type=get_content_type_for_model(model)
|
2008-07-19 07:54:34 +08:00
|
|
|
).select_related().order_by('action_time')
|
2013-02-05 07:57:59 +08:00
|
|
|
|
2015-01-01 05:25:00 +08:00
|
|
|
context = dict(self.admin_site.each_context(request),
|
2013-09-07 01:31:44 +08:00
|
|
|
title=_('Change history: %s') % force_text(obj),
|
|
|
|
action_list=action_list,
|
|
|
|
module_name=capfirst(force_text(opts.verbose_name_plural)),
|
|
|
|
object=obj,
|
|
|
|
opts=opts,
|
|
|
|
preserved_filters=self.get_preserved_filters(request),
|
|
|
|
)
|
2008-07-19 07:54:34 +08:00
|
|
|
context.update(extra_context or {})
|
2014-12-15 00:48:51 +08:00
|
|
|
|
|
|
|
request.current_app = self.admin_site.name
|
|
|
|
|
2011-04-23 02:17:16 +08:00
|
|
|
return TemplateResponse(request, self.object_history_template or [
|
2013-02-05 17:16:07 +08:00
|
|
|
"admin/%s/%s/object_history.html" % (app_label, opts.model_name),
|
2008-09-08 13:45:17 +08:00
|
|
|
"admin/%s/object_history.html" % app_label,
|
2008-07-19 07:54:34 +08:00
|
|
|
"admin/object_history.html"
|
2014-12-15 00:48:51 +08:00
|
|
|
], context)
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2014-11-28 02:34:14 +08:00
|
|
|
def _create_formsets(self, request, obj, change):
|
2013-07-29 23:50:41 +08:00
|
|
|
"Helper function to generate formsets for add/change_view."
|
|
|
|
formsets = []
|
2013-09-04 09:01:45 +08:00
|
|
|
inline_instances = []
|
2013-07-29 23:50:41 +08:00
|
|
|
prefixes = {}
|
|
|
|
get_formsets_args = [request]
|
2014-11-28 02:34:14 +08:00
|
|
|
if change:
|
2013-07-29 23:50:41 +08:00
|
|
|
get_formsets_args.append(obj)
|
2013-09-04 09:01:45 +08:00
|
|
|
for FormSet, inline in self.get_formsets_with_inlines(*get_formsets_args):
|
2013-07-29 23:50:41 +08:00
|
|
|
prefix = FormSet.get_default_prefix()
|
|
|
|
prefixes[prefix] = prefixes.get(prefix, 0) + 1
|
|
|
|
if prefixes[prefix] != 1 or not prefix:
|
|
|
|
prefix = "%s-%s" % (prefix, prefixes[prefix])
|
|
|
|
formset_params = {
|
|
|
|
'instance': obj,
|
|
|
|
'prefix': prefix,
|
|
|
|
'queryset': inline.get_queryset(request),
|
|
|
|
}
|
|
|
|
if request.method == 'POST':
|
|
|
|
formset_params.update({
|
|
|
|
'data': request.POST,
|
|
|
|
'files': request.FILES,
|
|
|
|
'save_as_new': '_saveasnew' in request.POST
|
|
|
|
})
|
|
|
|
formsets.append(FormSet(**formset_params))
|
2013-09-04 09:01:45 +08:00
|
|
|
inline_instances.append(inline)
|
|
|
|
return formsets, inline_instances
|
2013-07-29 23:50:41 +08:00
|
|
|
|
2013-06-23 09:48:09 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
class InlineModelAdmin(BaseModelAdmin):
|
|
|
|
"""
|
|
|
|
Options for inline editing of ``model`` instances.
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2014-07-06 02:28:30 +08:00
|
|
|
Provide ``fk_name`` to specify the attribute name of the ``ForeignKey``
|
|
|
|
from ``model`` to its parent. This is required if ``model`` has more than
|
|
|
|
one ``ForeignKey`` to its parent.
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
|
|
|
model = None
|
|
|
|
fk_name = None
|
2008-08-09 04:27:48 +08:00
|
|
|
formset = BaseInlineFormSet
|
2008-07-19 07:54:34 +08:00
|
|
|
extra = 3
|
2014-03-06 04:19:40 +08:00
|
|
|
min_num = None
|
2010-03-28 07:03:56 +08:00
|
|
|
max_num = None
|
2008-07-19 07:54:34 +08:00
|
|
|
template = None
|
|
|
|
verbose_name = None
|
|
|
|
verbose_name_plural = None
|
2010-02-24 01:14:50 +08:00
|
|
|
can_delete = True
|
2014-07-25 20:07:04 +08:00
|
|
|
show_change_link = False
|
2014-01-20 10:45:21 +08:00
|
|
|
checks_class = InlineModelAdminChecks
|
2015-11-07 23:46:50 +08:00
|
|
|
classes = None
|
2013-02-23 23:10:32 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def __init__(self, parent_model, admin_site):
|
|
|
|
self.admin_site = admin_site
|
|
|
|
self.parent_model = parent_model
|
|
|
|
self.opts = self.model._meta
|
2014-07-25 20:07:04 +08:00
|
|
|
self.has_registered_model = admin_site.is_registered(self.model)
|
2008-07-19 07:54:34 +08:00
|
|
|
super(InlineModelAdmin, self).__init__()
|
|
|
|
if self.verbose_name is None:
|
|
|
|
self.verbose_name = self.model._meta.verbose_name
|
|
|
|
if self.verbose_name_plural is None:
|
|
|
|
self.verbose_name_plural = self.model._meta.verbose_name_plural
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2011-08-11 22:07:39 +08:00
|
|
|
@property
|
|
|
|
def media(self):
|
2012-02-05 18:26:05 +08:00
|
|
|
extra = '' if settings.DEBUG else '.min'
|
2015-06-07 07:32:54 +08:00
|
|
|
js = ['vendor/jquery/jquery%s.js' % extra, 'jquery.init.js',
|
|
|
|
'inlines%s.js' % extra]
|
2008-08-16 04:33:45 +08:00
|
|
|
if self.filter_vertical or self.filter_horizontal:
|
2011-06-30 17:06:19 +08:00
|
|
|
js.extend(['SelectBox.js', 'SelectFilter2.js'])
|
2015-11-07 23:46:50 +08:00
|
|
|
if self.classes and 'collapse' in self.classes:
|
|
|
|
js.append('collapse%s.js' % extra)
|
2015-11-07 19:24:38 +08:00
|
|
|
return forms.Media(js=['admin/js/%s' % url for url in js])
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2013-05-31 01:48:10 +08:00
|
|
|
def get_extra(self, request, obj=None, **kwargs):
|
|
|
|
"""Hook for customizing the number of extra inline forms."""
|
|
|
|
return self.extra
|
|
|
|
|
2014-03-06 04:19:40 +08:00
|
|
|
def get_min_num(self, request, obj=None, **kwargs):
|
|
|
|
"""Hook for customizing the min number of inline forms."""
|
|
|
|
return self.min_num
|
|
|
|
|
2013-06-02 06:16:57 +08:00
|
|
|
def get_max_num(self, request, obj=None, **kwargs):
|
|
|
|
"""Hook for customizing the max number of extra inline forms."""
|
|
|
|
return self.max_num
|
|
|
|
|
2008-08-16 05:57:36 +08:00
|
|
|
def get_formset(self, request, obj=None, **kwargs):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""Returns a BaseInlineFormSet class for use in admin add/change views."""
|
2013-04-17 02:49:22 +08:00
|
|
|
if 'fields' in kwargs:
|
|
|
|
fields = kwargs.pop('fields')
|
2008-07-19 07:54:34 +08:00
|
|
|
else:
|
2013-04-17 02:49:22 +08:00
|
|
|
fields = flatten_fieldsets(self.get_fieldsets(request, obj))
|
2008-09-03 01:26:24 +08:00
|
|
|
if self.exclude is None:
|
|
|
|
exclude = []
|
|
|
|
else:
|
2008-09-27 13:57:10 +08:00
|
|
|
exclude = list(self.exclude)
|
2009-12-23 02:29:00 +08:00
|
|
|
exclude.extend(self.get_readonly_fields(request, obj))
|
2011-08-12 22:14:49 +08:00
|
|
|
if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
|
|
|
|
# Take the custom ModelForm's Meta.exclude into account only if the
|
|
|
|
# InlineModelAdmin doesn't define its own.
|
|
|
|
exclude.extend(self.form._meta.exclude)
|
2014-07-06 02:28:30 +08:00
|
|
|
# If exclude is an empty list we use None, since that's the actual
|
|
|
|
# default.
|
2009-12-23 02:29:00 +08:00
|
|
|
exclude = exclude or None
|
2011-10-07 08:41:25 +08:00
|
|
|
can_delete = self.can_delete and self.has_delete_permission(request, obj)
|
2008-08-16 05:57:36 +08:00
|
|
|
defaults = {
|
|
|
|
"form": self.form,
|
|
|
|
"formset": self.formset,
|
|
|
|
"fk_name": self.fk_name,
|
|
|
|
"fields": fields,
|
2009-12-23 02:29:00 +08:00
|
|
|
"exclude": exclude,
|
2011-03-28 09:40:43 +08:00
|
|
|
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
|
2013-05-31 01:48:10 +08:00
|
|
|
"extra": self.get_extra(request, obj, **kwargs),
|
2014-03-06 04:19:40 +08:00
|
|
|
"min_num": self.get_min_num(request, obj, **kwargs),
|
2013-06-02 06:16:57 +08:00
|
|
|
"max_num": self.get_max_num(request, obj, **kwargs),
|
2011-10-07 08:41:25 +08:00
|
|
|
"can_delete": can_delete,
|
2008-08-16 05:57:36 +08:00
|
|
|
}
|
2013-02-24 02:44:54 +08:00
|
|
|
|
2008-08-16 05:57:36 +08:00
|
|
|
defaults.update(kwargs)
|
2013-02-24 02:44:54 +08:00
|
|
|
base_model_form = defaults['form']
|
|
|
|
|
|
|
|
class DeleteProtectedModelForm(base_model_form):
|
|
|
|
def hand_clean_DELETE(self):
|
|
|
|
"""
|
|
|
|
We don't validate the 'DELETE' field itself because on
|
|
|
|
templates it's not rendered using the field information, but
|
|
|
|
just using a generic "deletion_field" of the InlineModelAdmin.
|
|
|
|
"""
|
|
|
|
if self.cleaned_data.get(DELETION_FIELD_NAME, False):
|
|
|
|
using = router.db_for_write(self._meta.model)
|
|
|
|
collector = NestedObjects(using=using)
|
2014-12-04 21:22:45 +08:00
|
|
|
if self.instance.pk is None:
|
|
|
|
return
|
2013-02-24 02:44:54 +08:00
|
|
|
collector.collect([self.instance])
|
|
|
|
if collector.protected:
|
|
|
|
objs = []
|
|
|
|
for p in collector.protected:
|
|
|
|
objs.append(
|
2014-09-04 20:15:09 +08:00
|
|
|
# Translators: Model verbose name and instance representation,
|
|
|
|
# suitable to be an item in a list.
|
2013-02-24 02:44:54 +08:00
|
|
|
_('%(class_name)s %(instance)s') % {
|
|
|
|
'class_name': p._meta.verbose_name,
|
|
|
|
'instance': p}
|
|
|
|
)
|
2013-06-06 02:55:05 +08:00
|
|
|
params = {'class_name': self._meta.model._meta.verbose_name,
|
|
|
|
'instance': self.instance,
|
|
|
|
'related_objects': get_text_list(objs, _('and'))}
|
2013-02-24 02:44:54 +08:00
|
|
|
msg = _("Deleting %(class_name)s %(instance)s would require "
|
|
|
|
"deleting the following protected related objects: "
|
2013-06-06 02:55:05 +08:00
|
|
|
"%(related_objects)s")
|
|
|
|
raise ValidationError(msg, code='deleting_protected', params=params)
|
2013-02-24 02:44:54 +08:00
|
|
|
|
|
|
|
def is_valid(self):
|
|
|
|
result = super(DeleteProtectedModelForm, self).is_valid()
|
|
|
|
self.hand_clean_DELETE()
|
|
|
|
return result
|
|
|
|
|
|
|
|
defaults['form'] = DeleteProtectedModelForm
|
2013-02-22 05:56:55 +08:00
|
|
|
|
|
|
|
if defaults['fields'] is None and not modelform_defines_fields(defaults['form']):
|
|
|
|
defaults['fields'] = forms.ALL_FIELDS
|
|
|
|
|
2008-08-16 05:57:36 +08:00
|
|
|
return inlineformset_factory(self.parent_model, self.model, **defaults)
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2013-07-31 13:52:11 +08:00
|
|
|
def get_fields(self, request, obj=None):
|
|
|
|
if self.fields:
|
|
|
|
return self.fields
|
2013-04-17 02:49:22 +08:00
|
|
|
form = self.get_formset(request, obj, fields=None).form
|
2013-07-31 13:52:11 +08:00
|
|
|
return list(form.base_fields) + list(self.get_readonly_fields(request, obj))
|
2009-03-18 17:19:24 +08:00
|
|
|
|
2013-03-08 22:15:23 +08:00
|
|
|
def get_queryset(self, request):
|
|
|
|
queryset = super(InlineModelAdmin, self).get_queryset(request)
|
2011-10-07 08:41:25 +08:00
|
|
|
if not self.has_change_permission(request):
|
|
|
|
queryset = queryset.none()
|
|
|
|
return queryset
|
|
|
|
|
|
|
|
def has_add_permission(self, request):
|
|
|
|
if self.opts.auto_created:
|
|
|
|
# We're checking the rights to an auto-created intermediate model,
|
|
|
|
# which doesn't have its own individual permissions. The user needs
|
|
|
|
# to have the change permission for the related model in order to
|
|
|
|
# be able to do anything with the intermediate model.
|
|
|
|
return self.has_change_permission(request)
|
2013-06-23 09:48:09 +08:00
|
|
|
return super(InlineModelAdmin, self).has_add_permission(request)
|
2011-10-07 08:41:25 +08:00
|
|
|
|
|
|
|
def has_change_permission(self, request, obj=None):
|
|
|
|
opts = self.opts
|
|
|
|
if opts.auto_created:
|
|
|
|
# The model was auto-created as intermediary for a
|
|
|
|
# ManyToMany-relationship, find the target model
|
|
|
|
for field in opts.fields:
|
2015-02-26 22:19:17 +08:00
|
|
|
if field.remote_field and field.remote_field.model != self.parent_model:
|
|
|
|
opts = field.remote_field.model._meta
|
2011-10-07 08:41:25 +08:00
|
|
|
break
|
2013-06-23 09:48:09 +08:00
|
|
|
codename = get_permission_codename('change', opts)
|
|
|
|
return request.user.has_perm("%s.%s" % (opts.app_label, codename))
|
2011-10-07 08:41:25 +08:00
|
|
|
|
|
|
|
def has_delete_permission(self, request, obj=None):
|
|
|
|
if self.opts.auto_created:
|
|
|
|
# We're checking the rights to an auto-created intermediate model,
|
|
|
|
# which doesn't have its own individual permissions. The user needs
|
|
|
|
# to have the change permission for the related model in order to
|
|
|
|
# be able to do anything with the intermediate model.
|
|
|
|
return self.has_change_permission(request, obj)
|
2013-06-23 09:48:09 +08:00
|
|
|
return super(InlineModelAdmin, self).has_delete_permission(request, obj)
|
2011-10-07 08:41:25 +08:00
|
|
|
|
2012-09-09 03:07:33 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
class StackedInline(InlineModelAdmin):
|
|
|
|
template = 'admin/edit_inline/stacked.html'
|
|
|
|
|
2012-09-09 03:07:33 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
class TabularInline(InlineModelAdmin):
|
|
|
|
template = 'admin/edit_inline/tabular.html'
|