2006-11-25 14:33:59 +08:00
|
|
|
"""
|
2006-12-15 13:46:11 +08:00
|
|
|
Helper functions for creating Form classes from Django models
|
|
|
|
and database field objects.
|
2006-11-25 14:33:59 +08:00
|
|
|
"""
|
2015-01-07 08:16:35 +08:00
|
|
|
from itertools import chain
|
2013-02-22 05:56:55 +08:00
|
|
|
|
2014-02-27 05:48:20 +08:00
|
|
|
from django.core.exceptions import (
|
2015-01-28 20:35:27 +08:00
|
|
|
NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError,
|
|
|
|
)
|
|
|
|
from django.forms.fields import ChoiceField, Field
|
|
|
|
from django.forms.forms import BaseForm, DeclarativeFieldsMetaclass
|
2011-10-18 00:56:18 +08:00
|
|
|
from django.forms.formsets import BaseFormSet, formset_factory
|
2013-09-17 00:52:05 +08:00
|
|
|
from django.forms.utils import ErrorList
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.forms.widgets import (
|
2020-02-03 00:30:34 +08:00
|
|
|
HiddenInput, MultipleHiddenInput, RadioSelect, SelectMultiple,
|
2015-01-28 20:35:27 +08:00
|
|
|
)
|
|
|
|
from django.utils.text import capfirst, get_text_list
|
2017-01-27 03:58:33 +08:00
|
|
|
from django.utils.translation import gettext, gettext_lazy as _
|
2006-12-15 13:46:11 +08:00
|
|
|
|
2007-05-17 05:20:35 +08:00
|
|
|
__all__ = (
|
2007-12-03 03:29:54 +08:00
|
|
|
'ModelForm', 'BaseModelForm', 'model_to_dict', 'fields_for_model',
|
2015-08-07 05:27:21 +08:00
|
|
|
'ModelChoiceField', 'ModelMultipleChoiceField', 'ALL_FIELDS',
|
|
|
|
'BaseModelFormSet', 'modelformset_factory', 'BaseInlineFormSet',
|
|
|
|
'inlineformset_factory', 'modelform_factory',
|
2007-05-17 05:20:35 +08:00
|
|
|
)
|
2006-11-25 14:33:59 +08:00
|
|
|
|
2013-02-22 05:56:55 +08:00
|
|
|
ALL_FIELDS = '__all__'
|
|
|
|
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def construct_instance(form, instance, fields=None, exclude=None):
|
2007-01-09 13:49:47 +08:00
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Construct and return a model instance from the bound ``form``'s
|
|
|
|
``cleaned_data``, but do not save the returned instance to the database.
|
2007-01-09 13:49:47 +08:00
|
|
|
"""
|
2006-12-28 10:34:53 +08:00
|
|
|
from django.db import models
|
2008-07-19 07:54:34 +08:00
|
|
|
opts = instance._meta
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2007-05-15 00:24:51 +08:00
|
|
|
cleaned_data = form.cleaned_data
|
2008-11-05 03:48:35 +08:00
|
|
|
file_field_list = []
|
2007-01-28 12:56:54 +08:00
|
|
|
for f in opts.fields:
|
2007-10-30 07:52:17 +08:00
|
|
|
if not f.editable or isinstance(f, models.AutoField) \
|
2014-03-31 03:11:05 +08:00
|
|
|
or f.name not in cleaned_data:
|
2007-01-09 13:49:47 +08:00
|
|
|
continue
|
2010-10-13 12:46:33 +08:00
|
|
|
if fields is not None and f.name not in fields:
|
2007-05-12 22:42:46 +08:00
|
|
|
continue
|
2008-08-31 17:49:55 +08:00
|
|
|
if exclude and f.name in exclude:
|
|
|
|
continue
|
2016-08-12 03:18:48 +08:00
|
|
|
# Leave defaults for fields that aren't in POST data, except for
|
|
|
|
# checkbox inputs because they don't appear in POST data if not checked.
|
2019-06-01 01:05:37 +08:00
|
|
|
if (
|
|
|
|
f.has_default() and
|
|
|
|
form[f.name].field.widget.value_omitted_from_data(form.data, form.files, form.add_prefix(f.name)) and
|
|
|
|
cleaned_data.get(f.name) in form[f.name].field.empty_values
|
|
|
|
):
|
2016-08-12 03:18:48 +08:00
|
|
|
continue
|
2008-11-05 03:48:35 +08:00
|
|
|
# Defer saving file-type fields until after the other fields, so a
|
|
|
|
# callable upload_to can use the values from other fields.
|
|
|
|
if isinstance(f, models.FileField):
|
|
|
|
file_field_list.append(f)
|
|
|
|
else:
|
|
|
|
f.save_form_data(instance, cleaned_data[f.name])
|
2008-12-23 13:50:51 +08:00
|
|
|
|
2008-11-05 03:48:35 +08:00
|
|
|
for f in file_field_list:
|
2007-10-30 07:52:17 +08:00
|
|
|
f.save_form_data(instance, cleaned_data[f.name])
|
2008-12-23 13:50:51 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
return instance
|
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2007-12-03 03:29:54 +08:00
|
|
|
# ModelForms #################################################################
|
|
|
|
|
|
|
|
def model_to_dict(instance, fields=None, exclude=None):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return a dict containing the data in ``instance`` suitable for passing as
|
2007-12-03 03:29:54 +08:00
|
|
|
a Form's ``initial`` keyword argument.
|
2007-12-17 19:59:53 +08:00
|
|
|
|
2017-01-25 05:23:56 +08:00
|
|
|
``fields`` is an optional list of field names. If provided, return only the
|
|
|
|
named.
|
2007-12-17 19:59:53 +08:00
|
|
|
|
2017-01-25 05:23:56 +08:00
|
|
|
``exclude`` is an optional list of field names. If provided, exclude the
|
|
|
|
named from the returned dict, even if they are listed in the ``fields``
|
|
|
|
argument.
|
2007-12-03 03:29:54 +08:00
|
|
|
"""
|
|
|
|
opts = instance._meta
|
|
|
|
data = {}
|
2016-03-21 01:10:55 +08:00
|
|
|
for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many):
|
2013-11-13 03:35:52 +08:00
|
|
|
if not getattr(f, 'editable', False):
|
2007-12-03 03:29:54 +08:00
|
|
|
continue
|
2019-04-03 15:05:15 +08:00
|
|
|
if fields is not None and f.name not in fields:
|
2007-12-03 03:29:54 +08:00
|
|
|
continue
|
|
|
|
if exclude and f.name in exclude:
|
|
|
|
continue
|
2016-05-11 22:12:59 +08:00
|
|
|
data[f.name] = f.value_from_object(instance)
|
2007-12-03 03:29:54 +08:00
|
|
|
return data
|
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2017-06-29 11:30:19 +08:00
|
|
|
def apply_limit_choices_to_to_formfield(formfield):
|
|
|
|
"""Apply limit_choices_to to the formfield's queryset if needed."""
|
2020-08-17 11:39:10 +08:00
|
|
|
from django.db.models import Exists, OuterRef, Q
|
2017-06-29 11:30:19 +08:00
|
|
|
if hasattr(formfield, 'queryset') and hasattr(formfield, 'get_limit_choices_to'):
|
|
|
|
limit_choices_to = formfield.get_limit_choices_to()
|
2020-08-17 11:39:10 +08:00
|
|
|
if limit_choices_to:
|
|
|
|
complex_filter = limit_choices_to
|
|
|
|
if not isinstance(complex_filter, Q):
|
|
|
|
complex_filter = Q(**limit_choices_to)
|
|
|
|
complex_filter &= Q(pk=OuterRef('pk'))
|
|
|
|
# Use Exists() to avoid potential duplicates.
|
|
|
|
formfield.queryset = formfield.queryset.filter(
|
|
|
|
Exists(formfield.queryset.model._base_manager.filter(complex_filter)),
|
|
|
|
)
|
2017-06-29 11:30:19 +08:00
|
|
|
|
|
|
|
|
2013-04-04 03:51:37 +08:00
|
|
|
def fields_for_model(model, fields=None, exclude=None, widgets=None,
|
|
|
|
formfield_callback=None, localized_fields=None,
|
2015-02-07 05:19:23 +08:00
|
|
|
labels=None, help_texts=None, error_messages=None,
|
2017-06-29 11:30:19 +08:00
|
|
|
field_classes=None, *, apply_limit_choices_to=True):
|
2007-12-03 03:29:54 +08:00
|
|
|
"""
|
2019-02-05 19:22:08 +08:00
|
|
|
Return a dictionary containing form fields for the given model.
|
2007-12-03 03:29:54 +08:00
|
|
|
|
2017-01-25 05:23:56 +08:00
|
|
|
``fields`` is an optional list of field names. If provided, return only the
|
|
|
|
named fields.
|
2007-12-17 19:59:53 +08:00
|
|
|
|
2017-01-25 05:23:56 +08:00
|
|
|
``exclude`` is an optional list of field names. If provided, exclude the
|
|
|
|
named fields from the returned fields, even if they are listed in the
|
|
|
|
``fields`` argument.
|
2013-01-11 18:59:17 +08:00
|
|
|
|
2013-04-04 03:51:37 +08:00
|
|
|
``widgets`` is a dictionary of model field names mapped to a widget.
|
|
|
|
|
2015-02-07 05:19:23 +08:00
|
|
|
``formfield_callback`` is a callable that takes a model field and returns
|
|
|
|
a form field.
|
|
|
|
|
2013-04-04 03:51:37 +08:00
|
|
|
``localized_fields`` is a list of names of fields which should be localized.
|
|
|
|
|
|
|
|
``labels`` is a dictionary of model field names mapped to a label.
|
|
|
|
|
|
|
|
``help_texts`` is a dictionary of model field names mapped to a help text.
|
|
|
|
|
|
|
|
``error_messages`` is a dictionary of model field names mapped to a
|
|
|
|
dictionary of error messages.
|
2013-01-11 18:59:17 +08:00
|
|
|
|
2015-02-07 05:19:23 +08:00
|
|
|
``field_classes`` is a dictionary of model field names mapped to a form
|
|
|
|
field class.
|
2017-06-29 11:30:19 +08:00
|
|
|
|
|
|
|
``apply_limit_choices_to`` is a boolean indicating if limit_choices_to
|
|
|
|
should be applied to a field's queryset.
|
2007-12-03 03:29:54 +08:00
|
|
|
"""
|
2019-02-05 19:22:08 +08:00
|
|
|
field_dict = {}
|
2010-03-31 15:43:52 +08:00
|
|
|
ignored = []
|
2007-12-03 03:29:54 +08:00
|
|
|
opts = model._meta
|
2013-11-17 02:51:47 +08:00
|
|
|
# Avoid circular import
|
2019-08-20 15:54:41 +08:00
|
|
|
from django.db.models import Field as ModelField
|
2016-03-21 01:10:55 +08:00
|
|
|
sortable_private_fields = [f for f in opts.private_fields if isinstance(f, ModelField)]
|
|
|
|
for f in sorted(chain(opts.concrete_fields, sortable_private_fields, opts.many_to_many)):
|
2013-11-13 03:35:52 +08:00
|
|
|
if not getattr(f, 'editable', False):
|
2016-02-20 21:40:07 +08:00
|
|
|
if (fields is not None and f.name in fields and
|
|
|
|
(exclude is None or f.name not in exclude)):
|
|
|
|
raise FieldError(
|
|
|
|
"'%s' cannot be specified for %s model form as it is a non-editable field" % (
|
|
|
|
f.name, model.__name__)
|
|
|
|
)
|
2007-12-03 03:29:54 +08:00
|
|
|
continue
|
2014-03-31 03:11:05 +08:00
|
|
|
if fields is not None and f.name not in fields:
|
2007-12-03 03:29:54 +08:00
|
|
|
continue
|
|
|
|
if exclude and f.name in exclude:
|
|
|
|
continue
|
2013-05-18 20:13:00 +08:00
|
|
|
|
|
|
|
kwargs = {}
|
2010-01-11 03:23:42 +08:00
|
|
|
if widgets and f.name in widgets:
|
2013-05-18 20:13:00 +08:00
|
|
|
kwargs['widget'] = widgets[f.name]
|
|
|
|
if localized_fields == ALL_FIELDS or (localized_fields and f.name in localized_fields):
|
|
|
|
kwargs['localize'] = True
|
2013-04-04 03:51:37 +08:00
|
|
|
if labels and f.name in labels:
|
|
|
|
kwargs['label'] = labels[f.name]
|
|
|
|
if help_texts and f.name in help_texts:
|
|
|
|
kwargs['help_text'] = help_texts[f.name]
|
|
|
|
if error_messages and f.name in error_messages:
|
|
|
|
kwargs['error_messages'] = error_messages[f.name]
|
2015-02-07 05:19:23 +08:00
|
|
|
if field_classes and f.name in field_classes:
|
|
|
|
kwargs['form_class'] = field_classes[f.name]
|
2010-09-11 06:46:22 +08:00
|
|
|
|
|
|
|
if formfield_callback is None:
|
|
|
|
formfield = f.formfield(**kwargs)
|
|
|
|
elif not callable(formfield_callback):
|
|
|
|
raise TypeError('formfield_callback must be a function or callable')
|
|
|
|
else:
|
|
|
|
formfield = formfield_callback(f, **kwargs)
|
|
|
|
|
2007-12-03 03:29:54 +08:00
|
|
|
if formfield:
|
2017-06-29 11:30:19 +08:00
|
|
|
if apply_limit_choices_to:
|
|
|
|
apply_limit_choices_to_to_formfield(formfield)
|
2019-02-05 19:22:08 +08:00
|
|
|
field_dict[f.name] = formfield
|
2010-03-31 15:43:52 +08:00
|
|
|
else:
|
|
|
|
ignored.append(f.name)
|
2009-03-15 13:05:26 +08:00
|
|
|
if fields:
|
2019-02-05 19:22:08 +08:00
|
|
|
field_dict = {
|
|
|
|
f: field_dict.get(f) for f in fields
|
|
|
|
if (not exclude or f not in exclude) and f not in ignored
|
|
|
|
}
|
2009-03-15 13:05:26 +08:00
|
|
|
return field_dict
|
2007-12-03 03:29:54 +08:00
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class ModelFormOptions:
|
2007-12-03 03:29:54 +08:00
|
|
|
def __init__(self, options=None):
|
|
|
|
self.model = getattr(options, 'model', None)
|
|
|
|
self.fields = getattr(options, 'fields', None)
|
|
|
|
self.exclude = getattr(options, 'exclude', None)
|
2010-01-11 03:23:42 +08:00
|
|
|
self.widgets = getattr(options, 'widgets', None)
|
2013-05-18 20:13:00 +08:00
|
|
|
self.localized_fields = getattr(options, 'localized_fields', None)
|
2013-04-04 03:51:37 +08:00
|
|
|
self.labels = getattr(options, 'labels', None)
|
|
|
|
self.help_texts = getattr(options, 'help_texts', None)
|
|
|
|
self.error_messages = getattr(options, 'error_messages', None)
|
2015-02-07 05:19:23 +08:00
|
|
|
self.field_classes = getattr(options, 'field_classes', None)
|
2007-12-03 03:29:54 +08:00
|
|
|
|
2008-02-14 20:56:49 +08:00
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
class ModelFormMetaclass(DeclarativeFieldsMetaclass):
|
|
|
|
def __new__(mcs, name, bases, attrs):
|
2016-01-27 12:34:00 +08:00
|
|
|
base_formfield_callback = None
|
|
|
|
for b in bases:
|
|
|
|
if hasattr(b, 'Meta') and hasattr(b.Meta, 'formfield_callback'):
|
|
|
|
base_formfield_callback = b.Meta.formfield_callback
|
|
|
|
break
|
|
|
|
|
|
|
|
formfield_callback = attrs.pop('formfield_callback', base_formfield_callback)
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2019-11-28 22:34:29 +08:00
|
|
|
new_class = super().__new__(mcs, name, bases, attrs)
|
2013-07-21 03:25:27 +08:00
|
|
|
|
|
|
|
if bases == (BaseModelForm,):
|
2008-07-06 20:29:40 +08:00
|
|
|
return new_class
|
2008-02-14 20:56:49 +08:00
|
|
|
|
|
|
|
opts = new_class._meta = ModelFormOptions(getattr(new_class, 'Meta', None))
|
2013-04-08 00:41:35 +08:00
|
|
|
|
|
|
|
# We check if a string was passed to `fields` or `exclude`,
|
|
|
|
# which is likely to be a mistake where the user typed ('foo') instead
|
|
|
|
# of ('foo',)
|
2013-05-18 20:13:00 +08:00
|
|
|
for opt in ['fields', 'exclude', 'localized_fields']:
|
2013-04-08 00:41:35 +08:00
|
|
|
value = getattr(opts, opt)
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(value, str) and value != ALL_FIELDS:
|
2013-04-08 00:41:35 +08:00
|
|
|
msg = ("%(model)s.Meta.%(opt)s cannot be a string. "
|
|
|
|
"Did you mean to type: ('%(value)s',)?" % {
|
|
|
|
'model': new_class.__name__,
|
|
|
|
'opt': opt,
|
|
|
|
'value': value,
|
|
|
|
})
|
|
|
|
raise TypeError(msg)
|
|
|
|
|
2008-02-14 20:56:49 +08:00
|
|
|
if opts.model:
|
|
|
|
# If a model is defined, extract form fields from it.
|
2013-02-22 05:56:55 +08:00
|
|
|
if opts.fields is None and opts.exclude is None:
|
2014-03-22 08:44:34 +08:00
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"Creating a ModelForm without either the 'fields' attribute "
|
|
|
|
"or the 'exclude' attribute is prohibited; form %s "
|
|
|
|
"needs updating." % name
|
|
|
|
)
|
2013-02-22 05:56:55 +08:00
|
|
|
|
|
|
|
if opts.fields == ALL_FIELDS:
|
2013-07-21 03:25:27 +08:00
|
|
|
# Sentinel for fields_for_model to indicate "get the list of
|
2013-02-22 05:56:55 +08:00
|
|
|
# fields from the model"
|
|
|
|
opts.fields = None
|
|
|
|
|
2017-06-29 11:30:19 +08:00
|
|
|
fields = fields_for_model(
|
|
|
|
opts.model, opts.fields, opts.exclude, opts.widgets,
|
|
|
|
formfield_callback, opts.localized_fields, opts.labels,
|
|
|
|
opts.help_texts, opts.error_messages, opts.field_classes,
|
|
|
|
# limit_choices_to will be applied during ModelForm.__init__().
|
|
|
|
apply_limit_choices_to=False,
|
|
|
|
)
|
2013-05-18 20:13:00 +08:00
|
|
|
|
2010-09-11 09:39:16 +08:00
|
|
|
# make sure opts.fields doesn't specify an invalid field
|
2017-07-29 22:16:43 +08:00
|
|
|
none_model_fields = {k for k, v in fields.items() if not v}
|
|
|
|
missing_fields = none_model_fields.difference(new_class.declared_fields)
|
2010-09-11 09:39:16 +08:00
|
|
|
if missing_fields:
|
|
|
|
message = 'Unknown field(s) (%s) specified for %s'
|
|
|
|
message = message % (', '.join(missing_fields),
|
|
|
|
opts.model.__name__)
|
|
|
|
raise FieldError(message)
|
2008-02-15 17:42:50 +08:00
|
|
|
# Override default model fields with any custom declared ones
|
|
|
|
# (plus, include all the other declared fields).
|
2013-07-21 03:25:27 +08:00
|
|
|
fields.update(new_class.declared_fields)
|
2008-02-14 20:56:49 +08:00
|
|
|
else:
|
2013-07-21 03:25:27 +08:00
|
|
|
fields = new_class.declared_fields
|
|
|
|
|
2008-02-14 20:56:49 +08:00
|
|
|
new_class.base_fields = fields
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2008-02-14 20:56:49 +08:00
|
|
|
return new_class
|
2007-12-03 03:29:54 +08:00
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2007-12-03 03:29:54 +08:00
|
|
|
class BaseModelForm(BaseForm):
|
2007-12-13 10:48:04 +08:00
|
|
|
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
|
2013-07-13 17:43:14 +08:00
|
|
|
initial=None, error_class=ErrorList, label_suffix=None,
|
2018-03-29 22:09:00 +08:00
|
|
|
empty_permitted=False, instance=None, use_required_attribute=None,
|
|
|
|
renderer=None):
|
2007-12-03 03:29:54 +08:00
|
|
|
opts = self._meta
|
2013-02-24 01:29:56 +08:00
|
|
|
if opts.model is None:
|
|
|
|
raise ValueError('ModelForm has no model class specified.')
|
2007-12-13 10:48:04 +08:00
|
|
|
if instance is None:
|
|
|
|
# if we didn't get an instance, instantiate a new one
|
|
|
|
self.instance = opts.model()
|
|
|
|
object_data = {}
|
|
|
|
else:
|
|
|
|
self.instance = instance
|
|
|
|
object_data = model_to_dict(instance, opts.fields, opts.exclude)
|
2007-12-03 03:29:54 +08:00
|
|
|
# if initial was provided, it should override the values from instance
|
|
|
|
if initial is not None:
|
|
|
|
object_data.update(initial)
|
2010-03-07 02:42:56 +08:00
|
|
|
# self._validate_unique will be set to True by BaseModelForm.clean().
|
|
|
|
# It is False by default so overriding self.clean() and failing to call
|
|
|
|
# super will stop validate_unique from being called.
|
|
|
|
self._validate_unique = False
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(
|
2016-03-29 02:02:04 +08:00
|
|
|
data, files, auto_id, prefix, object_data, error_class,
|
|
|
|
label_suffix, empty_permitted, use_required_attribute=use_required_attribute,
|
2018-03-29 22:09:00 +08:00
|
|
|
renderer=renderer,
|
2016-03-29 02:02:04 +08:00
|
|
|
)
|
2017-06-29 11:30:19 +08:00
|
|
|
for formfield in self.fields.values():
|
|
|
|
apply_limit_choices_to_to_formfield(formfield)
|
2009-04-30 21:47:39 +08:00
|
|
|
|
2010-01-12 10:29:45 +08:00
|
|
|
def _get_validation_exclusions(self):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
For backwards-compatibility, exclude several types of fields from model
|
|
|
|
validation. See tickets #12507, #12521, #12553.
|
2010-01-12 10:29:45 +08:00
|
|
|
"""
|
|
|
|
exclude = []
|
|
|
|
# Build up a list of fields that should be excluded from model field
|
|
|
|
# validation and unique checks.
|
|
|
|
for f in self.instance._meta.fields:
|
|
|
|
field = f.name
|
|
|
|
# Exclude fields that aren't on the form. The developer may be
|
|
|
|
# adding these values to the model after form validation.
|
|
|
|
if field not in self.fields:
|
|
|
|
exclude.append(f.name)
|
2010-02-23 07:06:09 +08:00
|
|
|
|
|
|
|
# Don't perform model validation on fields that were defined
|
|
|
|
# manually on the form and excluded via the ModelForm's Meta
|
|
|
|
# class. See #12901.
|
|
|
|
elif self._meta.fields and field not in self._meta.fields:
|
|
|
|
exclude.append(f.name)
|
2010-02-26 01:18:27 +08:00
|
|
|
elif self._meta.exclude and field in self._meta.exclude:
|
|
|
|
exclude.append(f.name)
|
2010-02-23 07:06:09 +08:00
|
|
|
|
2010-01-12 10:29:45 +08:00
|
|
|
# Exclude fields that failed form validation. There's no need for
|
|
|
|
# the model fields to validate them as well.
|
2017-05-28 07:08:46 +08:00
|
|
|
elif field in self._errors:
|
2010-01-12 10:29:45 +08:00
|
|
|
exclude.append(f.name)
|
2010-02-23 07:06:09 +08:00
|
|
|
|
2010-03-18 10:03:07 +08:00
|
|
|
# Exclude empty fields that are not required by the form, if the
|
|
|
|
# underlying model field is required. This keeps the model field
|
|
|
|
# from raising a required error. Note: don't exclude the field from
|
2011-08-12 22:14:15 +08:00
|
|
|
# validation if the model field allows blanks. If it does, the blank
|
2010-03-18 10:03:07 +08:00
|
|
|
# value may be included in a unique check, so cannot be excluded
|
|
|
|
# from validation.
|
2010-01-12 10:29:45 +08:00
|
|
|
else:
|
|
|
|
form_field = self.fields[field]
|
2015-05-14 02:51:18 +08:00
|
|
|
field_value = self.cleaned_data.get(field)
|
2013-03-07 16:21:59 +08:00
|
|
|
if not f.blank and not form_field.required and field_value in form_field.empty_values:
|
2010-01-12 10:29:45 +08:00
|
|
|
exclude.append(f.name)
|
|
|
|
return exclude
|
|
|
|
|
2008-09-02 03:08:08 +08:00
|
|
|
def clean(self):
|
2010-03-07 02:42:56 +08:00
|
|
|
self._validate_unique = True
|
2010-01-21 10:28:03 +08:00
|
|
|
return self.cleaned_data
|
|
|
|
|
2013-11-12 01:56:01 +08:00
|
|
|
def _update_errors(self, errors):
|
|
|
|
# Override any validation error messages defined at the model level
|
2014-02-04 02:31:27 +08:00
|
|
|
# with those defined at the form level.
|
|
|
|
opts = self._meta
|
2015-04-30 15:57:30 +08:00
|
|
|
|
|
|
|
# Allow the model generated by construct_instance() to raise
|
|
|
|
# ValidationError and have them handled in the same way as others.
|
|
|
|
if hasattr(errors, 'error_dict'):
|
|
|
|
error_dict = errors.error_dict
|
|
|
|
else:
|
|
|
|
error_dict = {NON_FIELD_ERRORS: errors}
|
|
|
|
|
|
|
|
for field, messages in error_dict.items():
|
2014-02-04 02:31:27 +08:00
|
|
|
if (field == NON_FIELD_ERRORS and opts.error_messages and
|
|
|
|
NON_FIELD_ERRORS in opts.error_messages):
|
|
|
|
error_messages = opts.error_messages[NON_FIELD_ERRORS]
|
|
|
|
elif field in self.fields:
|
|
|
|
error_messages = self.fields[field].error_messages
|
|
|
|
else:
|
2013-11-12 01:56:01 +08:00
|
|
|
continue
|
2014-02-04 02:31:27 +08:00
|
|
|
|
2013-11-12 01:56:01 +08:00
|
|
|
for message in messages:
|
|
|
|
if (isinstance(message, ValidationError) and
|
2014-02-04 02:31:27 +08:00
|
|
|
message.code in error_messages):
|
|
|
|
message.message = error_messages[message.code]
|
2013-11-12 01:56:01 +08:00
|
|
|
|
|
|
|
self.add_error(None, errors)
|
|
|
|
|
2010-03-07 02:42:56 +08:00
|
|
|
def _post_clean(self):
|
2010-01-05 11:56:19 +08:00
|
|
|
opts = self._meta
|
2010-03-07 02:42:56 +08:00
|
|
|
|
2010-04-27 23:05:38 +08:00
|
|
|
exclude = self._get_validation_exclusions()
|
|
|
|
|
|
|
|
# Foreign Keys being used to represent inline relationships
|
|
|
|
# are excluded from basic field value validation. This is for two
|
|
|
|
# reasons: firstly, the value may not be supplied (#12507; the
|
|
|
|
# case of providing new values to the admin); secondly the
|
|
|
|
# object being referred to may not yet fully exist (#12749).
|
|
|
|
# However, these fields *must* be included in uniqueness checks,
|
|
|
|
# so this can't be part of _get_validation_exclusions().
|
2013-11-12 01:56:01 +08:00
|
|
|
for name, field in self.fields.items():
|
2010-04-27 23:05:38 +08:00
|
|
|
if isinstance(field, InlineForeignKeyField):
|
2013-11-12 01:56:01 +08:00
|
|
|
exclude.append(name)
|
2010-04-27 23:05:38 +08:00
|
|
|
|
2015-11-15 00:38:27 +08:00
|
|
|
try:
|
|
|
|
self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
|
|
|
|
except ValidationError as e:
|
|
|
|
self._update_errors(e)
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
try:
|
2013-11-12 01:56:01 +08:00
|
|
|
self.instance.full_clean(exclude=exclude, validate_unique=False)
|
2012-04-29 00:09:37 +08:00
|
|
|
except ValidationError as e:
|
2013-04-05 03:21:57 +08:00
|
|
|
self._update_errors(e)
|
2010-03-07 02:42:56 +08:00
|
|
|
|
|
|
|
# Validate uniqueness if needed.
|
|
|
|
if self._validate_unique:
|
|
|
|
self.validate_unique()
|
2010-01-21 10:28:03 +08:00
|
|
|
|
|
|
|
def validate_unique(self):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Call the instance's validate_unique() method and update the form's
|
2010-01-21 10:28:03 +08:00
|
|
|
validation errors if any were raised.
|
|
|
|
"""
|
|
|
|
exclude = self._get_validation_exclusions()
|
|
|
|
try:
|
|
|
|
self.instance.validate_unique(exclude=exclude)
|
2012-04-29 00:09:37 +08:00
|
|
|
except ValidationError as e:
|
2013-04-05 03:21:57 +08:00
|
|
|
self._update_errors(e)
|
2007-12-03 03:29:54 +08:00
|
|
|
|
2015-08-07 05:27:21 +08:00
|
|
|
def _save_m2m(self):
|
2007-12-03 03:29:54 +08:00
|
|
|
"""
|
2015-08-07 05:27:21 +08:00
|
|
|
Save the many-to-many fields and generic relations for this form.
|
|
|
|
"""
|
|
|
|
cleaned_data = self.cleaned_data
|
|
|
|
exclude = self._meta.exclude
|
|
|
|
fields = self._meta.fields
|
|
|
|
opts = self.instance._meta
|
|
|
|
# Note that for historical reasons we want to include also
|
2016-03-21 01:10:55 +08:00
|
|
|
# private_fields here. (GenericRelation was previously a fake
|
2015-08-07 05:27:21 +08:00
|
|
|
# m2m field).
|
2016-03-21 01:10:55 +08:00
|
|
|
for f in chain(opts.many_to_many, opts.private_fields):
|
2015-08-07 05:27:21 +08:00
|
|
|
if not hasattr(f, 'save_form_data'):
|
|
|
|
continue
|
|
|
|
if fields and f.name not in fields:
|
|
|
|
continue
|
|
|
|
if exclude and f.name in exclude:
|
|
|
|
continue
|
|
|
|
if f.name in cleaned_data:
|
|
|
|
f.save_form_data(self.instance, cleaned_data[f.name])
|
2007-12-03 03:29:54 +08:00
|
|
|
|
2015-08-07 05:27:21 +08:00
|
|
|
def save(self, commit=True):
|
2007-12-03 03:29:54 +08:00
|
|
|
"""
|
2015-08-07 05:27:21 +08:00
|
|
|
Save this form's self.instance object if commit=True. Otherwise, add
|
|
|
|
a save_m2m() method to the form which can be called after the instance
|
|
|
|
is saved manually at a later time. Return the model instance.
|
|
|
|
"""
|
|
|
|
if self.errors:
|
|
|
|
raise ValueError(
|
|
|
|
"The %s could not be %s because the data didn't validate." % (
|
|
|
|
self.instance._meta.object_name,
|
|
|
|
'created' if self.instance._state.adding else 'changed',
|
|
|
|
)
|
|
|
|
)
|
|
|
|
if commit:
|
|
|
|
# If committing, save the instance and the m2m data immediately.
|
|
|
|
self.instance.save()
|
|
|
|
self._save_m2m()
|
2007-12-03 03:29:54 +08:00
|
|
|
else:
|
2015-08-07 05:27:21 +08:00
|
|
|
# If not committing, add a method to the form to allow deferred
|
|
|
|
# saving of m2m data.
|
|
|
|
self.save_m2m = self._save_m2m
|
|
|
|
return self.instance
|
2007-12-03 03:29:54 +08:00
|
|
|
|
2008-12-23 13:50:51 +08:00
|
|
|
save.alters_data = True
|
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2017-01-07 19:11:46 +08:00
|
|
|
class ModelForm(BaseModelForm, metaclass=ModelFormMetaclass):
|
2012-07-21 03:20:42 +08:00
|
|
|
pass
|
2007-12-03 03:29:54 +08:00
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def modelform_factory(model, form=ModelForm, fields=None, exclude=None,
|
2013-04-04 03:51:37 +08:00
|
|
|
formfield_callback=None, widgets=None, localized_fields=None,
|
2015-02-07 05:19:23 +08:00
|
|
|
labels=None, help_texts=None, error_messages=None,
|
|
|
|
field_classes=None):
|
2013-01-11 18:59:17 +08:00
|
|
|
"""
|
2019-06-20 20:26:08 +08:00
|
|
|
Return a ModelForm containing form fields for the given model. You can
|
|
|
|
optionally pass a `form` argument to use as a starting point for
|
|
|
|
constructing the ModelForm.
|
2013-01-11 18:59:17 +08:00
|
|
|
|
2017-01-25 05:23:56 +08:00
|
|
|
``fields`` is an optional list of field names. If provided, include only
|
|
|
|
the named fields in the returned fields. If omitted or '__all__', use all
|
|
|
|
fields.
|
2013-01-11 18:59:17 +08:00
|
|
|
|
2017-01-25 05:23:56 +08:00
|
|
|
``exclude`` is an optional list of field names. If provided, exclude the
|
|
|
|
named fields from the returned fields, even if they are listed in the
|
|
|
|
``fields`` argument.
|
2013-01-11 18:59:17 +08:00
|
|
|
|
|
|
|
``widgets`` is a dictionary of model field names mapped to a widget.
|
|
|
|
|
2013-05-18 20:13:00 +08:00
|
|
|
``localized_fields`` is a list of names of fields which should be localized.
|
|
|
|
|
2013-01-11 18:59:17 +08:00
|
|
|
``formfield_callback`` is a callable that takes a model field and returns
|
|
|
|
a form field.
|
2013-04-04 03:51:37 +08:00
|
|
|
|
|
|
|
``labels`` is a dictionary of model field names mapped to a label.
|
|
|
|
|
|
|
|
``help_texts`` is a dictionary of model field names mapped to a help text.
|
|
|
|
|
|
|
|
``error_messages`` is a dictionary of model field names mapped to a
|
|
|
|
dictionary of error messages.
|
2015-02-07 05:19:23 +08:00
|
|
|
|
|
|
|
``field_classes`` is a dictionary of model field names mapped to a form
|
|
|
|
field class.
|
2013-01-11 18:59:17 +08:00
|
|
|
"""
|
2009-04-22 23:48:51 +08:00
|
|
|
# Create the inner Meta class. FIXME: ideally, we should be able to
|
|
|
|
# construct a ModelForm without creating and passing in a temporary
|
|
|
|
# inner class.
|
|
|
|
|
|
|
|
# Build up a list of attributes that the Meta object will have.
|
|
|
|
attrs = {'model': model}
|
|
|
|
if fields is not None:
|
|
|
|
attrs['fields'] = fields
|
|
|
|
if exclude is not None:
|
|
|
|
attrs['exclude'] = exclude
|
2011-08-23 12:08:24 +08:00
|
|
|
if widgets is not None:
|
|
|
|
attrs['widgets'] = widgets
|
2013-05-18 20:13:00 +08:00
|
|
|
if localized_fields is not None:
|
|
|
|
attrs['localized_fields'] = localized_fields
|
2013-04-04 03:51:37 +08:00
|
|
|
if labels is not None:
|
|
|
|
attrs['labels'] = labels
|
|
|
|
if help_texts is not None:
|
|
|
|
attrs['help_texts'] = help_texts
|
|
|
|
if error_messages is not None:
|
|
|
|
attrs['error_messages'] = error_messages
|
2015-02-07 05:19:23 +08:00
|
|
|
if field_classes is not None:
|
|
|
|
attrs['field_classes'] = field_classes
|
2009-04-22 23:48:51 +08:00
|
|
|
|
|
|
|
# If parent form class already has an inner Meta, the Meta we're
|
|
|
|
# creating needs to inherit from the parent's inner meta.
|
2017-01-19 15:39:46 +08:00
|
|
|
bases = (form.Meta,) if hasattr(form, 'Meta') else ()
|
2017-01-19 22:48:01 +08:00
|
|
|
Meta = type('Meta', bases, attrs)
|
2016-01-27 12:34:00 +08:00
|
|
|
if formfield_callback:
|
|
|
|
Meta.formfield_callback = staticmethod(formfield_callback)
|
2009-04-22 23:48:51 +08:00
|
|
|
# Give this new form class a reasonable name.
|
2017-01-19 22:48:01 +08:00
|
|
|
class_name = model.__name__ + 'Form'
|
2009-04-22 23:48:51 +08:00
|
|
|
|
|
|
|
# Class attributes for the new form class.
|
|
|
|
form_class_attrs = {
|
|
|
|
'Meta': Meta,
|
|
|
|
'formfield_callback': formfield_callback
|
|
|
|
}
|
|
|
|
|
2013-02-22 05:56:55 +08:00
|
|
|
if (getattr(Meta, 'fields', None) is None and
|
2013-11-26 17:43:46 +08:00
|
|
|
getattr(Meta, 'exclude', None) is None):
|
2014-03-22 08:44:34 +08:00
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"Calling modelform_factory without defining 'fields' or "
|
|
|
|
"'exclude' explicitly is prohibited."
|
|
|
|
)
|
2013-02-22 05:56:55 +08:00
|
|
|
|
2015-01-20 22:54:12 +08:00
|
|
|
# Instantiate type(form) in order to use the same metaclass as form.
|
2012-08-15 05:44:46 +08:00
|
|
|
return type(form)(class_name, (form,), form_class_attrs)
|
2008-07-19 07:54:34 +08:00
|
|
|
|
|
|
|
|
|
|
|
# ModelFormSets ##############################################################
|
|
|
|
|
|
|
|
class BaseModelFormSet(BaseFormSet):
|
|
|
|
"""
|
|
|
|
A ``FormSet`` for editing a queryset and/or adding new objects to it.
|
|
|
|
"""
|
|
|
|
model = None
|
|
|
|
|
2016-03-25 08:04:25 +08:00
|
|
|
# Set of fields that must be unique among forms of this set.
|
|
|
|
unique_fields = set()
|
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
|
2017-02-02 00:41:56 +08:00
|
|
|
queryset=None, *, initial=None, **kwargs):
|
2008-07-19 07:54:34 +08:00
|
|
|
self.queryset = queryset
|
2017-02-02 00:41:56 +08:00
|
|
|
self.initial_extra = initial
|
2017-12-11 20:08:45 +08:00
|
|
|
super().__init__(**{'data': data, 'files': files, 'auto_id': auto_id, 'prefix': prefix, **kwargs})
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2009-03-30 23:58:52 +08:00
|
|
|
def initial_form_count(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return the number of forms that are required in this FormSet."""
|
2018-08-21 22:02:03 +08:00
|
|
|
if not self.is_bound:
|
2009-03-30 23:58:52 +08:00
|
|
|
return len(self.get_queryset())
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().initial_form_count()
|
2009-03-30 23:58:52 +08:00
|
|
|
|
2009-07-03 11:05:17 +08:00
|
|
|
def _existing_object(self, pk):
|
|
|
|
if not hasattr(self, '_object_dict'):
|
2014-12-07 05:00:09 +08:00
|
|
|
self._object_dict = {o.pk: o for o in self.get_queryset()}
|
2009-07-03 11:05:17 +08:00
|
|
|
return self._object_dict.get(pk)
|
|
|
|
|
2013-10-31 03:14:23 +08:00
|
|
|
def _get_to_python(self, field):
|
|
|
|
"""
|
|
|
|
If the field is a related field, fetch the concrete field's (that
|
2014-11-22 04:58:53 +08:00
|
|
|
is, the ultimate pointed-to field's) to_python.
|
2013-10-31 03:14:23 +08:00
|
|
|
"""
|
2015-02-26 22:19:17 +08:00
|
|
|
while field.remote_field is not None:
|
|
|
|
field = field.remote_field.get_related_field()
|
2013-10-31 03:14:23 +08:00
|
|
|
return field.to_python
|
|
|
|
|
2008-09-02 03:08:08 +08:00
|
|
|
def _construct_form(self, i, **kwargs):
|
2018-01-12 22:05:16 +08:00
|
|
|
pk_required = i < self.initial_form_count()
|
|
|
|
if pk_required:
|
2017-06-27 06:00:30 +08:00
|
|
|
if self.is_bound:
|
|
|
|
pk_key = '%s-%s' % (self.add_prefix(i), self.model._meta.pk.name)
|
|
|
|
try:
|
|
|
|
pk = self.data[pk_key]
|
|
|
|
except KeyError:
|
|
|
|
# The primary key is missing. The user may have tampered
|
|
|
|
# with POST data.
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
to_python = self._get_to_python(self.model._meta.pk)
|
|
|
|
try:
|
|
|
|
pk = to_python(pk)
|
|
|
|
except ValidationError:
|
|
|
|
# The primary key exists but is an invalid value. The
|
|
|
|
# user may have tampered with POST data.
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
kwargs['instance'] = self._existing_object(pk)
|
|
|
|
else:
|
|
|
|
kwargs['instance'] = self.get_queryset()[i]
|
|
|
|
elif self.initial_extra:
|
2012-01-15 09:36:14 +08:00
|
|
|
# Set initial values for extra forms
|
2017-09-07 20:16:21 +08:00
|
|
|
try:
|
2013-11-04 02:08:55 +08:00
|
|
|
kwargs['initial'] = self.initial_extra[i - self.initial_form_count()]
|
2017-09-07 20:16:21 +08:00
|
|
|
except IndexError:
|
|
|
|
pass
|
2017-06-27 06:00:30 +08:00
|
|
|
form = super()._construct_form(i, **kwargs)
|
|
|
|
if pk_required:
|
|
|
|
form.fields[self.model._meta.pk.name].required = True
|
|
|
|
return form
|
2008-09-02 03:08:08 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def get_queryset(self):
|
2008-09-02 03:08:08 +08:00
|
|
|
if not hasattr(self, '_queryset'):
|
|
|
|
if self.queryset is not None:
|
|
|
|
qs = self.queryset
|
|
|
|
else:
|
2013-03-08 22:15:23 +08:00
|
|
|
qs = self.model._default_manager.get_queryset()
|
2009-04-23 06:16:42 +08:00
|
|
|
|
|
|
|
# If the queryset isn't already ordered we need to add an
|
|
|
|
# artificial ordering here to make sure that all formsets
|
|
|
|
# constructed from this queryset have the same form order.
|
|
|
|
if not qs.ordered:
|
|
|
|
qs = qs.order_by(self.model._meta.pk.name)
|
|
|
|
|
2010-03-28 07:03:56 +08:00
|
|
|
# Removed queryset limiting here. As per discussion re: #13023
|
|
|
|
# on django-dev, max_num should not prevent existing
|
|
|
|
# related objects/inlines from being displayed.
|
|
|
|
self._queryset = qs
|
2008-09-02 03:08:08 +08:00
|
|
|
return self._queryset
|
2008-07-19 07:54:34 +08:00
|
|
|
|
|
|
|
def save_new(self, form, commit=True):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Save and return a new model instance for the given form."""
|
2009-03-30 23:58:52 +08:00
|
|
|
return form.save(commit=commit)
|
2008-07-19 07:54:34 +08:00
|
|
|
|
|
|
|
def save_existing(self, form, instance, commit=True):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Save and return an existing model instance for the given form."""
|
2009-03-30 23:58:52 +08:00
|
|
|
return form.save(commit=commit)
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2015-07-10 13:29:09 +08:00
|
|
|
def delete_existing(self, obj, commit=True):
|
|
|
|
"""Deletes an existing model instance."""
|
|
|
|
if commit:
|
|
|
|
obj.delete()
|
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def save(self, commit=True):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""
|
|
|
|
Save model instances for every form, adding and changing instances
|
|
|
|
as necessary, and return the list of instances.
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
|
|
|
if not commit:
|
|
|
|
self.saved_forms = []
|
2013-10-22 18:21:07 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def save_m2m():
|
|
|
|
for form in self.saved_forms:
|
|
|
|
form.save_m2m()
|
|
|
|
self.save_m2m = save_m2m
|
|
|
|
return self.save_existing_objects(commit) + self.save_new_objects(commit)
|
|
|
|
|
2013-02-23 20:01:28 +08:00
|
|
|
save.alters_data = True
|
|
|
|
|
2009-05-07 20:17:52 +08:00
|
|
|
def clean(self):
|
|
|
|
self.validate_unique()
|
|
|
|
|
|
|
|
def validate_unique(self):
|
2010-01-12 10:29:45 +08:00
|
|
|
# Collect unique_checks and date_checks to run from all the forms.
|
|
|
|
all_unique_checks = set()
|
|
|
|
all_date_checks = set()
|
2013-02-09 04:30:06 +08:00
|
|
|
forms_to_delete = self.deleted_forms
|
|
|
|
valid_forms = [form for form in self.forms if form.is_valid() and form not in forms_to_delete]
|
|
|
|
for form in valid_forms:
|
2010-01-12 10:29:45 +08:00
|
|
|
exclude = form._get_validation_exclusions()
|
|
|
|
unique_checks, date_checks = form.instance._get_unique_checks(exclude=exclude)
|
2017-07-29 22:16:43 +08:00
|
|
|
all_unique_checks.update(unique_checks)
|
|
|
|
all_date_checks.update(date_checks)
|
2010-01-12 10:29:45 +08:00
|
|
|
|
2009-05-07 20:17:52 +08:00
|
|
|
errors = []
|
|
|
|
# Do each of the unique checks (unique and unique_together)
|
2010-03-17 03:32:11 +08:00
|
|
|
for uclass, unique_check in all_unique_checks:
|
2009-05-07 20:17:52 +08:00
|
|
|
seen_data = set()
|
2013-02-09 04:30:06 +08:00
|
|
|
for form in valid_forms:
|
2016-03-25 08:04:25 +08:00
|
|
|
# Get the data for the set of fields that must be unique among the forms.
|
|
|
|
row_data = (
|
|
|
|
field if field in self.unique_fields else form.cleaned_data[field]
|
|
|
|
for field in unique_check if field in form.cleaned_data
|
|
|
|
)
|
2013-08-14 16:05:01 +08:00
|
|
|
# Reduce Model instances to their primary key values
|
2018-05-27 18:06:37 +08:00
|
|
|
row_data = tuple(
|
|
|
|
d._get_pk_val() if hasattr(d, '_get_pk_val')
|
|
|
|
# Prevent "unhashable type: list" errors later on.
|
|
|
|
else tuple(d) if isinstance(d, list)
|
|
|
|
else d for d in row_data
|
|
|
|
)
|
2014-03-31 03:11:05 +08:00
|
|
|
if row_data and None not in row_data:
|
2012-08-04 20:17:02 +08:00
|
|
|
# if we've already seen it then we have a uniqueness failure
|
2009-05-07 20:17:52 +08:00
|
|
|
if row_data in seen_data:
|
|
|
|
# poke error messages into the right places and mark
|
|
|
|
# the form as invalid
|
|
|
|
errors.append(self.get_unique_error_message(unique_check))
|
2011-02-05 14:33:16 +08:00
|
|
|
form._errors[NON_FIELD_ERRORS] = self.error_class([self.get_form_error()])
|
2012-08-04 20:17:02 +08:00
|
|
|
# remove the data from the cleaned_data dict since it was invalid
|
|
|
|
for field in unique_check:
|
|
|
|
if field in form.cleaned_data:
|
|
|
|
del form.cleaned_data[field]
|
2009-05-07 20:17:52 +08:00
|
|
|
# mark the data as seen
|
|
|
|
seen_data.add(row_data)
|
|
|
|
# iterate over each of the date checks now
|
2010-01-12 10:29:45 +08:00
|
|
|
for date_check in all_date_checks:
|
2009-05-07 20:17:52 +08:00
|
|
|
seen_data = set()
|
2010-03-17 03:32:11 +08:00
|
|
|
uclass, lookup, field, unique_for = date_check
|
2013-02-09 04:30:06 +08:00
|
|
|
for form in valid_forms:
|
2009-05-07 20:17:52 +08:00
|
|
|
# see if we have data for both fields
|
2016-04-04 08:37:32 +08:00
|
|
|
if (form.cleaned_data and form.cleaned_data[field] is not None and
|
|
|
|
form.cleaned_data[unique_for] is not None):
|
2009-05-07 20:17:52 +08:00
|
|
|
# if it's a date lookup we need to get the data for all the fields
|
|
|
|
if lookup == 'date':
|
|
|
|
date = form.cleaned_data[unique_for]
|
|
|
|
date_data = (date.year, date.month, date.day)
|
|
|
|
# otherwise it's just the attribute on the date/datetime
|
|
|
|
# object
|
|
|
|
else:
|
|
|
|
date_data = (getattr(form.cleaned_data[unique_for], lookup),)
|
|
|
|
data = (form.cleaned_data[field],) + date_data
|
2012-08-04 20:17:02 +08:00
|
|
|
# if we've already seen it then we have a uniqueness failure
|
2009-05-07 20:17:52 +08:00
|
|
|
if data in seen_data:
|
|
|
|
# poke error messages into the right places and mark
|
|
|
|
# the form as invalid
|
|
|
|
errors.append(self.get_date_error_message(date_check))
|
2011-02-05 14:33:16 +08:00
|
|
|
form._errors[NON_FIELD_ERRORS] = self.error_class([self.get_form_error()])
|
2012-08-04 20:17:02 +08:00
|
|
|
# remove the data from the cleaned_data dict since it was invalid
|
|
|
|
del form.cleaned_data[field]
|
|
|
|
# mark the data as seen
|
2009-05-07 20:17:52 +08:00
|
|
|
seen_data.add(data)
|
2013-11-12 01:56:01 +08:00
|
|
|
|
2009-05-07 20:17:52 +08:00
|
|
|
if errors:
|
|
|
|
raise ValidationError(errors)
|
|
|
|
|
|
|
|
def get_unique_error_message(self, unique_check):
|
|
|
|
if len(unique_check) == 1:
|
2017-01-27 03:58:33 +08:00
|
|
|
return gettext("Please correct the duplicate data for %(field)s.") % {
|
2009-05-07 20:17:52 +08:00
|
|
|
"field": unique_check[0],
|
|
|
|
}
|
|
|
|
else:
|
2017-01-27 03:58:33 +08:00
|
|
|
return gettext("Please correct the duplicate data for %(field)s, which must be unique.") % {
|
2016-12-29 23:27:49 +08:00
|
|
|
"field": get_text_list(unique_check, _("and")),
|
2013-10-18 17:02:43 +08:00
|
|
|
}
|
2009-05-07 20:17:52 +08:00
|
|
|
|
|
|
|
def get_date_error_message(self, date_check):
|
2017-01-27 03:58:33 +08:00
|
|
|
return gettext(
|
2016-03-29 06:33:29 +08:00
|
|
|
"Please correct the duplicate data for %(field_name)s "
|
|
|
|
"which must be unique for the %(lookup)s in %(date_field)s."
|
|
|
|
) % {
|
2010-03-17 03:32:11 +08:00
|
|
|
'field_name': date_check[2],
|
|
|
|
'date_field': date_check[3],
|
2016-12-29 23:27:49 +08:00
|
|
|
'lookup': str(date_check[1]),
|
2009-05-07 20:17:52 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
def get_form_error(self):
|
2017-01-27 03:58:33 +08:00
|
|
|
return gettext("Please correct the duplicate values below.")
|
2009-05-07 20:17:52 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def save_existing_objects(self, commit=True):
|
|
|
|
self.changed_objects = []
|
|
|
|
self.deleted_objects = []
|
2012-02-05 00:05:39 +08:00
|
|
|
if not self.initial_forms:
|
2008-07-19 07:54:34 +08:00
|
|
|
return []
|
|
|
|
|
|
|
|
saved_instances = []
|
2013-02-09 04:30:06 +08:00
|
|
|
forms_to_delete = self.deleted_forms
|
2008-07-19 07:54:34 +08:00
|
|
|
for form in self.initial_forms:
|
2013-10-31 03:14:23 +08:00
|
|
|
obj = form.instance
|
2016-12-07 02:06:58 +08:00
|
|
|
# If the pk is None, it means either:
|
|
|
|
# 1. The object is an unexpected empty model, created by invalid
|
|
|
|
# POST data such as an object outside the formset's queryset.
|
|
|
|
# 2. The object was already deleted from the database.
|
|
|
|
if obj.pk is None:
|
|
|
|
continue
|
2012-08-30 21:51:13 +08:00
|
|
|
if form in forms_to_delete:
|
2011-02-21 22:23:02 +08:00
|
|
|
self.deleted_objects.append(obj)
|
2015-07-10 13:29:09 +08:00
|
|
|
self.delete_existing(obj, commit=commit)
|
2013-10-31 03:14:23 +08:00
|
|
|
elif form.has_changed():
|
2009-04-01 03:55:20 +08:00
|
|
|
self.changed_objects.append((obj, form.changed_data))
|
|
|
|
saved_instances.append(self.save_existing(form, obj, commit=commit))
|
|
|
|
if not commit:
|
|
|
|
self.saved_forms.append(form)
|
2008-07-19 07:54:34 +08:00
|
|
|
return saved_instances
|
|
|
|
|
|
|
|
def save_new_objects(self, commit=True):
|
|
|
|
self.new_objects = []
|
|
|
|
for form in self.extra_forms:
|
|
|
|
if not form.has_changed():
|
|
|
|
continue
|
|
|
|
# If someone has marked an add form for deletion, don't save the
|
|
|
|
# object.
|
2011-02-21 22:23:02 +08:00
|
|
|
if self.can_delete and self._should_delete_form(form):
|
|
|
|
continue
|
2008-07-19 07:54:34 +08:00
|
|
|
self.new_objects.append(self.save_new(form, commit=commit))
|
|
|
|
if not commit:
|
|
|
|
self.saved_forms.append(form)
|
|
|
|
return self.new_objects
|
|
|
|
|
|
|
|
def add_fields(self, form, index):
|
|
|
|
"""Add a hidden field for the object's primary key."""
|
2020-07-24 14:25:47 +08:00
|
|
|
from django.db.models import AutoField, ForeignKey, OneToOneField
|
2008-08-31 17:49:55 +08:00
|
|
|
self._pk_field = pk = self.model._meta.pk
|
2009-03-30 23:58:52 +08:00
|
|
|
# If a pk isn't editable, then it won't be on the form, so we need to
|
|
|
|
# add it here so we can tell which object is which when we get the
|
|
|
|
# data back. Generally, pk.editable should be false, but for some
|
|
|
|
# reason, auto_created pk fields and AutoField's editable attribute is
|
|
|
|
# True, so check for that as well.
|
2013-10-22 18:21:07 +08:00
|
|
|
|
2009-05-07 19:56:10 +08:00
|
|
|
def pk_is_not_editable(pk):
|
2015-09-12 07:33:12 +08:00
|
|
|
return (
|
|
|
|
(not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) or (
|
2016-04-04 08:37:32 +08:00
|
|
|
pk.remote_field and pk.remote_field.parent_link and
|
|
|
|
pk_is_not_editable(pk.remote_field.model._meta.pk)
|
2015-09-12 07:33:12 +08:00
|
|
|
)
|
|
|
|
)
|
2009-05-07 19:56:10 +08:00
|
|
|
if pk_is_not_editable(pk) or pk.name not in form.fields:
|
2009-07-03 11:05:17 +08:00
|
|
|
if form.is_bound:
|
2015-02-21 03:28:34 +08:00
|
|
|
# If we're adding the related instance, ignore its primary key
|
|
|
|
# as it could be an auto-generated default which isn't actually
|
|
|
|
# in the database.
|
|
|
|
pk_value = None if form.instance._state.adding else form.instance.pk
|
2009-07-03 11:05:17 +08:00
|
|
|
else:
|
|
|
|
try:
|
2010-01-26 23:02:53 +08:00
|
|
|
if index is not None:
|
|
|
|
pk_value = self.get_queryset()[index].pk
|
|
|
|
else:
|
|
|
|
pk_value = None
|
2009-07-03 11:05:17 +08:00
|
|
|
except IndexError:
|
|
|
|
pk_value = None
|
2017-09-14 03:00:45 +08:00
|
|
|
if isinstance(pk, (ForeignKey, OneToOneField)):
|
2015-02-26 22:19:17 +08:00
|
|
|
qs = pk.remote_field.model._default_manager.get_queryset()
|
2009-03-30 23:58:52 +08:00
|
|
|
else:
|
2013-03-08 22:15:23 +08:00
|
|
|
qs = self.model._default_manager.get_queryset()
|
2009-12-22 23:18:51 +08:00
|
|
|
qs = qs.using(form.instance._state.db)
|
2013-02-05 18:39:35 +08:00
|
|
|
if form._meta.widgets:
|
|
|
|
widget = form._meta.widgets.get(self._pk_field.name, HiddenInput)
|
|
|
|
else:
|
|
|
|
widget = HiddenInput
|
|
|
|
form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_value, required=False, widget=widget)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().add_fields(form, index)
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2010-09-11 06:46:22 +08:00
|
|
|
def modelformset_factory(model, form=ModelForm, formfield_callback=None,
|
2013-01-24 04:11:46 +08:00
|
|
|
formset=BaseModelFormSet, extra=1, can_delete=False,
|
2013-05-18 20:13:00 +08:00
|
|
|
can_order=False, max_num=None, fields=None, exclude=None,
|
2013-04-04 03:51:37 +08:00
|
|
|
widgets=None, validate_max=False, localized_fields=None,
|
2014-03-06 04:19:40 +08:00
|
|
|
labels=None, help_texts=None, error_messages=None,
|
2020-04-30 15:34:53 +08:00
|
|
|
min_num=None, validate_min=False, field_classes=None,
|
2020-06-20 05:46:25 +08:00
|
|
|
absolute_max=None, can_delete_extra=True):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return a FormSet class for the given Django model class."""
|
2013-02-22 05:56:55 +08:00
|
|
|
meta = getattr(form, 'Meta', None)
|
|
|
|
if (getattr(meta, 'fields', fields) is None and
|
2013-11-26 17:43:46 +08:00
|
|
|
getattr(meta, 'exclude', exclude) is None):
|
2014-03-22 08:44:34 +08:00
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"Calling modelformset_factory without defining 'fields' or "
|
|
|
|
"'exclude' explicitly is prohibited."
|
|
|
|
)
|
2013-02-22 05:56:55 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
form = modelform_factory(model, form=form, fields=fields, exclude=exclude,
|
2013-01-24 04:11:46 +08:00
|
|
|
formfield_callback=formfield_callback,
|
2013-04-04 03:51:37 +08:00
|
|
|
widgets=widgets, localized_fields=localized_fields,
|
2015-02-07 05:19:23 +08:00
|
|
|
labels=labels, help_texts=help_texts,
|
|
|
|
error_messages=error_messages, field_classes=field_classes)
|
2014-03-06 04:19:40 +08:00
|
|
|
FormSet = formset_factory(form, formset, extra=extra, min_num=min_num, max_num=max_num,
|
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 14:27:06 +08:00
|
|
|
can_order=can_order, can_delete=can_delete,
|
2020-04-30 15:34:53 +08:00
|
|
|
validate_min=validate_min, validate_max=validate_max,
|
2020-06-20 05:46:25 +08:00
|
|
|
absolute_max=absolute_max, can_delete_extra=can_delete_extra)
|
2008-07-19 07:54:34 +08:00
|
|
|
FormSet.model = model
|
|
|
|
return FormSet
|
|
|
|
|
|
|
|
|
|
|
|
# InlineFormSets #############################################################
|
|
|
|
|
2008-08-09 04:27:48 +08:00
|
|
|
class BaseInlineFormSet(BaseModelFormSet):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""A formset for child objects related to a parent."""
|
2008-07-23 12:46:31 +08:00
|
|
|
def __init__(self, data=None, files=None, instance=None,
|
2012-01-15 09:36:14 +08:00
|
|
|
save_as_new=False, prefix=None, queryset=None, **kwargs):
|
2008-10-29 04:01:03 +08:00
|
|
|
if instance is None:
|
2015-02-26 22:19:17 +08:00
|
|
|
self.instance = self.fk.remote_field.model()
|
2008-10-29 04:01:03 +08:00
|
|
|
else:
|
|
|
|
self.instance = instance
|
2008-07-19 07:54:34 +08:00
|
|
|
self.save_as_new = save_as_new
|
2009-12-16 22:52:29 +08:00
|
|
|
if queryset is None:
|
|
|
|
queryset = self.model._default_manager
|
2013-11-21 04:34:29 +08:00
|
|
|
if self.instance.pk is not None:
|
2012-12-29 06:16:13 +08:00
|
|
|
qs = queryset.filter(**{self.fk.name: self.instance})
|
|
|
|
else:
|
|
|
|
qs = queryset.none()
|
2016-03-25 08:04:25 +08:00
|
|
|
self.unique_fields = {self.fk.name}
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs)
|
Fixed #7830 -- Removed all of the remaining, deprecated, non-oldforms features:
* Support for representing files as strings was removed. Use `django.core.files.base.ContentFile` instead.
* Support for representing uploaded files as dictionaries was removed. Use `django.core.files.uploadedfile.SimpleUploadedFile` instead.
* The `filename`, `file_name`, `file_size`, and `chuck` properties of `UploadedFile` were removed. Use the `name`, `name`, `size`, and `chunks` properties instead, respectively.
* The `get_FIELD_filename`, `get_FIELD_url`, `get_FIELD_size`, and `save_FIELD_file` methods for Models with `FileField` fields were removed. Instead, use the `path`, `url`, and `size` attributes and `save` method on the field itself, respectively.
* The `get_FIELD_width` and `get_FIELD_height` methods for Models with `ImageField` fields were removed. Use the `width` and `height` attributes on the field itself instead.
* The dispatcher `connect`, `disconnect`, `send`, and `sendExact` functions were removed. Use the signal object's own `connect`, `disconnect`, `send`, and `send` methods instead, respectively.
* The `form_for_model` and `form_for_instance` functions were removed. Use a `ModelForm` subclass instead.
* Support for importing `django.newforms` was removed. Use `django.forms` instead.
* Support for importing `django.utils.images` was removed. Use `django.core.files.images` instead.
* Support for the `follow` argument in the `create_object` and `update_object` generic views was removed. Use the `django.forms` package and the new `form_class` argument instead.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8291 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-11 05:10:47 +08:00
|
|
|
|
2016-03-30 19:01:15 +08:00
|
|
|
# Add the generated field to form._meta.fields if it's defined to make
|
|
|
|
# sure validation isn't skipped on that field.
|
|
|
|
if self.form._meta.fields and self.fk.name not in self.form._meta.fields:
|
|
|
|
if isinstance(self.form._meta.fields, tuple):
|
|
|
|
self.form._meta.fields = list(self.form._meta.fields)
|
|
|
|
self.form._meta.fields.append(self.fk.name)
|
|
|
|
|
2009-03-30 23:58:52 +08:00
|
|
|
def initial_form_count(self):
|
2008-07-19 07:54:34 +08:00
|
|
|
if self.save_as_new:
|
2009-03-30 23:58:52 +08:00
|
|
|
return 0
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().initial_form_count()
|
2009-03-30 23:58:52 +08:00
|
|
|
|
2008-09-02 03:08:08 +08:00
|
|
|
def _construct_form(self, i, **kwargs):
|
2017-01-21 21:13:44 +08:00
|
|
|
form = super()._construct_form(i, **kwargs)
|
2008-09-02 03:08:08 +08:00
|
|
|
if self.save_as_new:
|
2017-05-02 07:58:28 +08:00
|
|
|
mutable = getattr(form.data, '_mutable', None)
|
|
|
|
# Allow modifying an immutable QueryDict.
|
|
|
|
if mutable is not None:
|
|
|
|
form.data._mutable = True
|
2008-09-02 03:08:08 +08:00
|
|
|
# Remove the primary key from the form's data, we are only
|
|
|
|
# creating new instances
|
|
|
|
form.data[form.add_prefix(self._pk_field.name)] = None
|
2009-04-02 08:01:15 +08:00
|
|
|
# Remove the foreign key from the form's data
|
|
|
|
form.data[form.add_prefix(self.fk.name)] = None
|
2017-05-02 07:58:28 +08:00
|
|
|
if mutable is not None:
|
|
|
|
form.data._mutable = mutable
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2012-07-23 11:12:36 +08:00
|
|
|
# Set the fk value here so that the form can do its validation.
|
2014-07-09 03:58:14 +08:00
|
|
|
fk_value = self.instance.pk
|
2015-02-26 22:19:17 +08:00
|
|
|
if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.pk.name:
|
|
|
|
fk_value = getattr(self.instance, self.fk.remote_field.field_name)
|
2014-07-09 03:58:14 +08:00
|
|
|
fk_value = getattr(fk_value, 'pk', fk_value)
|
|
|
|
setattr(form.instance, self.fk.get_attname(), fk_value)
|
2008-09-02 03:08:08 +08:00
|
|
|
return form
|
2008-12-23 13:50:51 +08:00
|
|
|
|
2011-05-02 00:46:02 +08:00
|
|
|
@classmethod
|
2009-03-10 19:19:26 +08:00
|
|
|
def get_default_prefix(cls):
|
2015-02-26 22:19:17 +08:00
|
|
|
return cls.fk.remote_field.get_accessor_name(model=cls.model).replace('+', '')
|
2009-03-10 19:19:26 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def save_new(self, form, commit=True):
|
2015-02-24 17:54:05 +08:00
|
|
|
# Ensure the latest copy of the related instance is present on each
|
|
|
|
# form (it may have been saved after the formset was originally
|
|
|
|
# instantiated).
|
|
|
|
setattr(form.instance, self.fk.name, self.instance)
|
2018-06-08 09:14:19 +08:00
|
|
|
return super().save_new(form, commit=commit)
|
2008-10-08 18:09:44 +08:00
|
|
|
|
2008-08-31 17:49:55 +08:00
|
|
|
def add_fields(self, form, index):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().add_fields(form, index)
|
2008-08-31 17:49:55 +08:00
|
|
|
if self._pk_field == self.fk:
|
2010-02-23 07:06:09 +08:00
|
|
|
name = self._pk_field.name
|
|
|
|
kwargs = {'pk_field': True}
|
2008-11-01 06:07:05 +08:00
|
|
|
else:
|
2009-03-31 08:03:34 +08:00
|
|
|
# The foreign key field might not be on the form, so we poke at the
|
|
|
|
# Model field to get the label, since we need that for error messages.
|
2010-02-23 07:06:09 +08:00
|
|
|
name = self.fk.name
|
2009-05-15 20:44:51 +08:00
|
|
|
kwargs = {
|
2010-02-23 07:06:09 +08:00
|
|
|
'label': getattr(form.fields.get(name), 'label', capfirst(self.fk.verbose_name))
|
2009-05-15 20:44:51 +08:00
|
|
|
}
|
2018-12-12 03:41:21 +08:00
|
|
|
|
|
|
|
# The InlineForeignKeyField assumes that the foreign key relation is
|
|
|
|
# based on the parent model's pk. If this isn't the case, set to_field
|
|
|
|
# to correctly resolve the initial form value.
|
|
|
|
if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.pk.name:
|
|
|
|
kwargs['to_field'] = self.fk.remote_field.field_name
|
2010-02-23 07:06:09 +08:00
|
|
|
|
2015-06-06 04:04:24 +08:00
|
|
|
# If we're adding a new object, ignore a parent's auto-generated key
|
2015-02-21 03:28:34 +08:00
|
|
|
# as it will be regenerated on the save request.
|
2015-06-06 04:04:24 +08:00
|
|
|
if self.instance._state.adding:
|
|
|
|
if kwargs.get('to_field') is not None:
|
|
|
|
to_field = self.instance._meta.get_field(kwargs['to_field'])
|
|
|
|
else:
|
|
|
|
to_field = self.instance._meta.pk
|
|
|
|
if to_field.has_default():
|
|
|
|
setattr(self.instance, to_field.attname, None)
|
2015-02-21 03:28:34 +08:00
|
|
|
|
2010-02-23 07:06:09 +08:00
|
|
|
form.fields[name] = InlineForeignKeyField(self.instance, **kwargs)
|
|
|
|
|
2009-05-07 20:17:52 +08:00
|
|
|
def get_unique_error_message(self, unique_check):
|
|
|
|
unique_check = [field for field in unique_check if field != self.fk.name]
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().get_unique_error_message(unique_check)
|
2009-05-07 20:17:52 +08:00
|
|
|
|
2010-04-27 23:05:38 +08:00
|
|
|
|
2009-05-11 05:09:38 +08:00
|
|
|
def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Find and return the ForeignKey from model to parent if there is one
|
|
|
|
(return None if can_fail is True and no such field exists). If fk_name is
|
2014-07-06 02:28:30 +08:00
|
|
|
provided, assume it is the name of the ForeignKey field. Unless can_fail is
|
2017-01-25 05:23:56 +08:00
|
|
|
True, raise an exception if there isn't a ForeignKey from model to
|
2009-05-11 05:09:38 +08:00
|
|
|
parent_model.
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
|
|
|
# avoid circular import
|
|
|
|
from django.db.models import ForeignKey
|
|
|
|
opts = model._meta
|
|
|
|
if fk_name:
|
|
|
|
fks_to_parent = [f for f in opts.fields if f.name == fk_name]
|
|
|
|
if len(fks_to_parent) == 1:
|
|
|
|
fk = fks_to_parent[0]
|
2008-08-01 08:27:40 +08:00
|
|
|
if not isinstance(fk, ForeignKey) or \
|
2015-02-26 22:19:17 +08:00
|
|
|
(fk.remote_field.model != parent_model and
|
|
|
|
fk.remote_field.model not in parent_model._meta.get_parent_list()):
|
2014-01-20 10:45:21 +08:00
|
|
|
raise ValueError(
|
2015-04-27 05:05:50 +08:00
|
|
|
"fk_name '%s' is not a ForeignKey to '%s'." % (fk_name, parent_model._meta.label)
|
|
|
|
)
|
2017-11-30 00:54:34 +08:00
|
|
|
elif not fks_to_parent:
|
2014-01-20 10:45:21 +08:00
|
|
|
raise ValueError(
|
2015-04-27 05:05:50 +08:00
|
|
|
"'%s' has no field named '%s'." % (model._meta.label, fk_name)
|
|
|
|
)
|
2008-07-19 07:54:34 +08:00
|
|
|
else:
|
|
|
|
# Try to discover what the ForeignKey from model to parent_model is
|
2008-08-01 08:27:40 +08:00
|
|
|
fks_to_parent = [
|
Fixed #7830 -- Removed all of the remaining, deprecated, non-oldforms features:
* Support for representing files as strings was removed. Use `django.core.files.base.ContentFile` instead.
* Support for representing uploaded files as dictionaries was removed. Use `django.core.files.uploadedfile.SimpleUploadedFile` instead.
* The `filename`, `file_name`, `file_size`, and `chuck` properties of `UploadedFile` were removed. Use the `name`, `name`, `size`, and `chunks` properties instead, respectively.
* The `get_FIELD_filename`, `get_FIELD_url`, `get_FIELD_size`, and `save_FIELD_file` methods for Models with `FileField` fields were removed. Instead, use the `path`, `url`, and `size` attributes and `save` method on the field itself, respectively.
* The `get_FIELD_width` and `get_FIELD_height` methods for Models with `ImageField` fields were removed. Use the `width` and `height` attributes on the field itself instead.
* The dispatcher `connect`, `disconnect`, `send`, and `sendExact` functions were removed. Use the signal object's own `connect`, `disconnect`, `send`, and `send` methods instead, respectively.
* The `form_for_model` and `form_for_instance` functions were removed. Use a `ModelForm` subclass instead.
* Support for importing `django.newforms` was removed. Use `django.forms` instead.
* Support for importing `django.utils.images` was removed. Use `django.core.files.images` instead.
* Support for the `follow` argument in the `create_object` and `update_object` generic views was removed. Use the `django.forms` package and the new `form_class` argument instead.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8291 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-11 05:10:47 +08:00
|
|
|
f for f in opts.fields
|
2016-04-04 08:37:32 +08:00
|
|
|
if isinstance(f, ForeignKey) and (
|
|
|
|
f.remote_field.model == parent_model or
|
|
|
|
f.remote_field.model in parent_model._meta.get_parent_list()
|
|
|
|
)
|
2008-08-01 08:27:40 +08:00
|
|
|
]
|
2008-07-19 07:54:34 +08:00
|
|
|
if len(fks_to_parent) == 1:
|
|
|
|
fk = fks_to_parent[0]
|
2017-11-30 00:54:34 +08:00
|
|
|
elif not fks_to_parent:
|
2009-05-11 05:09:38 +08:00
|
|
|
if can_fail:
|
|
|
|
return
|
2014-01-20 10:45:21 +08:00
|
|
|
raise ValueError(
|
2015-04-27 05:05:50 +08:00
|
|
|
"'%s' has no ForeignKey to '%s'." % (
|
|
|
|
model._meta.label,
|
|
|
|
parent_model._meta.label,
|
2014-09-04 20:15:09 +08:00
|
|
|
)
|
|
|
|
)
|
2008-07-19 07:54:34 +08:00
|
|
|
else:
|
2014-01-20 10:45:21 +08:00
|
|
|
raise ValueError(
|
2019-12-17 05:16:39 +08:00
|
|
|
"'%s' has more than one ForeignKey to '%s'. You must specify "
|
|
|
|
"a 'fk_name' attribute." % (
|
2015-04-27 05:05:50 +08:00
|
|
|
model._meta.label,
|
|
|
|
parent_model._meta.label,
|
2014-09-04 20:15:09 +08:00
|
|
|
)
|
|
|
|
)
|
2008-07-19 07:54:34 +08:00
|
|
|
return fk
|
|
|
|
|
|
|
|
|
|
|
|
def inlineformset_factory(parent_model, model, form=ModelForm,
|
2008-08-09 04:27:48 +08:00
|
|
|
formset=BaseInlineFormSet, fk_name=None,
|
2013-05-18 20:13:00 +08:00
|
|
|
fields=None, exclude=None, extra=3, can_order=False,
|
|
|
|
can_delete=True, max_num=None, formfield_callback=None,
|
2013-04-04 03:51:37 +08:00
|
|
|
widgets=None, validate_max=False, localized_fields=None,
|
2014-03-06 04:19:40 +08:00
|
|
|
labels=None, help_texts=None, error_messages=None,
|
2020-04-30 15:34:53 +08:00
|
|
|
min_num=None, validate_min=False, field_classes=None,
|
2020-06-20 05:46:25 +08:00
|
|
|
absolute_max=None, can_delete_extra=True):
|
2008-07-19 07:54:34 +08:00
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return an ``InlineFormSet`` for the given kwargs.
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2017-01-25 05:23:56 +08:00
|
|
|
``fk_name`` must be provided if ``model`` has more than one ``ForeignKey``
|
2008-07-19 07:54:34 +08:00
|
|
|
to ``parent_model``.
|
|
|
|
"""
|
|
|
|
fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
|
2008-09-01 05:14:46 +08:00
|
|
|
# enforce a max_num=1 when the foreign key to the parent model is unique.
|
|
|
|
if fk.unique:
|
|
|
|
max_num = 1
|
|
|
|
kwargs = {
|
|
|
|
'form': form,
|
|
|
|
'formfield_callback': formfield_callback,
|
|
|
|
'formset': formset,
|
|
|
|
'extra': extra,
|
|
|
|
'can_delete': can_delete,
|
|
|
|
'can_order': can_order,
|
|
|
|
'fields': fields,
|
|
|
|
'exclude': exclude,
|
2014-03-06 04:19:40 +08:00
|
|
|
'min_num': min_num,
|
2008-09-01 05:14:46 +08:00
|
|
|
'max_num': max_num,
|
2013-01-24 04:11:46 +08:00
|
|
|
'widgets': widgets,
|
2014-03-06 04:19:40 +08:00
|
|
|
'validate_min': validate_min,
|
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 14:27:06 +08:00
|
|
|
'validate_max': validate_max,
|
2013-05-18 20:13:00 +08:00
|
|
|
'localized_fields': localized_fields,
|
2013-04-04 03:51:37 +08:00
|
|
|
'labels': labels,
|
|
|
|
'help_texts': help_texts,
|
|
|
|
'error_messages': error_messages,
|
2015-02-07 05:19:23 +08:00
|
|
|
'field_classes': field_classes,
|
2020-04-30 15:34:53 +08:00
|
|
|
'absolute_max': absolute_max,
|
2020-06-20 05:46:25 +08:00
|
|
|
'can_delete_extra': can_delete_extra,
|
2008-09-01 05:14:46 +08:00
|
|
|
}
|
|
|
|
FormSet = modelformset_factory(model, **kwargs)
|
2008-07-19 07:54:34 +08:00
|
|
|
FormSet.fk = fk
|
|
|
|
return FormSet
|
|
|
|
|
2007-12-03 03:29:54 +08:00
|
|
|
|
|
|
|
# Fields #####################################################################
|
|
|
|
|
2008-11-01 06:07:05 +08:00
|
|
|
class InlineForeignKeyField(Field):
|
|
|
|
"""
|
|
|
|
A basic integer field that deals with validating the given value to a
|
|
|
|
given parent instance in an inline.
|
|
|
|
"""
|
2013-01-26 03:50:46 +08:00
|
|
|
widget = HiddenInput
|
2008-11-01 06:07:05 +08:00
|
|
|
default_error_messages = {
|
2017-03-21 01:12:55 +08:00
|
|
|
'invalid_choice': _('The inline value did not match the parent instance.'),
|
2008-11-01 06:07:05 +08:00
|
|
|
}
|
2008-12-23 13:50:51 +08:00
|
|
|
|
2017-02-02 00:41:56 +08:00
|
|
|
def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs):
|
2008-11-01 06:07:05 +08:00
|
|
|
self.parent_instance = parent_instance
|
2017-02-02 00:41:56 +08:00
|
|
|
self.pk_field = pk_field
|
|
|
|
self.to_field = to_field
|
2008-11-01 06:07:05 +08:00
|
|
|
if self.parent_instance is not None:
|
2009-05-13 22:04:29 +08:00
|
|
|
if self.to_field:
|
|
|
|
kwargs["initial"] = getattr(self.parent_instance, self.to_field)
|
|
|
|
else:
|
|
|
|
kwargs["initial"] = self.parent_instance.pk
|
2008-11-01 06:07:05 +08:00
|
|
|
kwargs["required"] = False
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*args, **kwargs)
|
2008-12-23 13:50:51 +08:00
|
|
|
|
2008-11-01 06:07:05 +08:00
|
|
|
def clean(self, value):
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2008-11-01 06:07:05 +08:00
|
|
|
if self.pk_field:
|
|
|
|
return None
|
|
|
|
# if there is no value act as we did before.
|
|
|
|
return self.parent_instance
|
|
|
|
# ensure the we compare the values as equal types.
|
2009-05-13 22:04:29 +08:00
|
|
|
if self.to_field:
|
|
|
|
orig = getattr(self.parent_instance, self.to_field)
|
|
|
|
else:
|
|
|
|
orig = self.parent_instance.pk
|
2017-04-22 01:52:26 +08:00
|
|
|
if str(value) != str(orig):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')
|
2008-11-01 06:07:05 +08:00
|
|
|
return self.parent_instance
|
|
|
|
|
2014-08-07 10:56:23 +08:00
|
|
|
def has_changed(self, initial, data):
|
2013-01-26 03:50:46 +08:00
|
|
|
return False
|
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2019-11-18 07:41:23 +08:00
|
|
|
class ModelChoiceIteratorValue:
|
|
|
|
def __init__(self, value, instance):
|
|
|
|
self.value = value
|
|
|
|
self.instance = instance
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return str(self.value)
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
if isinstance(other, ModelChoiceIteratorValue):
|
|
|
|
other = other.value
|
|
|
|
return self.value == other
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class ModelChoiceIterator:
|
2008-03-20 07:10:45 +08:00
|
|
|
def __init__(self, field):
|
|
|
|
self.field = field
|
|
|
|
self.queryset = field.queryset
|
2007-02-21 13:14:28 +08:00
|
|
|
|
|
|
|
def __iter__(self):
|
2008-03-20 07:10:45 +08:00
|
|
|
if self.field.empty_label is not None:
|
2012-06-08 00:08:47 +08:00
|
|
|
yield ("", self.field.empty_label)
|
2018-02-24 13:12:09 +08:00
|
|
|
queryset = self.queryset
|
2015-10-06 06:21:56 +08:00
|
|
|
# Can't use iterator() when queryset uses prefetch_related()
|
2018-04-14 09:15:22 +08:00
|
|
|
if not queryset._prefetch_related_lookups:
|
2015-11-06 01:02:18 +08:00
|
|
|
queryset = queryset.iterator()
|
|
|
|
for obj in queryset:
|
2015-01-18 02:48:46 +08:00
|
|
|
yield self.choice(obj)
|
2008-09-02 06:43:38 +08:00
|
|
|
|
2009-12-14 01:46:52 +08:00
|
|
|
def __len__(self):
|
2018-04-14 09:15:22 +08:00
|
|
|
# count() adds a query but uses less memory since the QuerySet results
|
|
|
|
# won't be cached. In most cases, the choices will only be iterated on,
|
|
|
|
# and __len__() won't be called.
|
|
|
|
return self.queryset.count() + (1 if self.field.empty_label is not None else 0)
|
2009-12-14 01:46:52 +08:00
|
|
|
|
2018-04-14 09:39:10 +08:00
|
|
|
def __bool__(self):
|
|
|
|
return self.field.empty_label is not None or self.queryset.exists()
|
|
|
|
|
2008-09-02 06:43:38 +08:00
|
|
|
def choice(self, obj):
|
2019-11-18 07:41:23 +08:00
|
|
|
return (
|
|
|
|
ModelChoiceIteratorValue(self.field.prepare_value(obj), obj),
|
|
|
|
self.field.label_from_instance(obj),
|
|
|
|
)
|
2007-02-21 13:14:28 +08:00
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2007-02-20 10:42:07 +08:00
|
|
|
class ModelChoiceField(ChoiceField):
|
2007-10-30 07:52:17 +08:00
|
|
|
"""A ChoiceField whose choices are a model QuerySet."""
|
2007-02-21 13:14:28 +08:00
|
|
|
# This class is a subclass of ChoiceField for purity, but it doesn't
|
|
|
|
# actually use any of ChoiceField's implementation.
|
2007-11-19 04:25:23 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid_choice': _('Select a valid choice. That choice is not one of'
|
|
|
|
' the available choices.'),
|
2007-11-19 04:25:23 +08:00
|
|
|
}
|
2016-05-08 17:58:34 +08:00
|
|
|
iterator = ModelChoiceIterator
|
2007-10-30 07:52:17 +08:00
|
|
|
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, queryset, *, empty_label="---------",
|
2008-08-24 01:26:00 +08:00
|
|
|
required=True, widget=None, label=None, initial=None,
|
2014-02-02 03:23:31 +08:00
|
|
|
help_text='', to_field_name=None, limit_choices_to=None,
|
2020-02-03 00:30:34 +08:00
|
|
|
blank=False, **kwargs):
|
2007-02-21 13:14:28 +08:00
|
|
|
# Call Field instead of ChoiceField __init__() because we don't need
|
|
|
|
# ChoiceField.__init__().
|
2017-06-03 22:49:01 +08:00
|
|
|
Field.__init__(
|
|
|
|
self, required=required, widget=widget, label=label,
|
|
|
|
initial=initial, help_text=help_text, **kwargs
|
|
|
|
)
|
2020-02-03 00:30:34 +08:00
|
|
|
if (
|
|
|
|
(required and initial is not None) or
|
|
|
|
(isinstance(self.widget, RadioSelect) and not blank)
|
|
|
|
):
|
|
|
|
self.empty_label = None
|
|
|
|
else:
|
|
|
|
self.empty_label = empty_label
|
2007-11-13 22:36:29 +08:00
|
|
|
self.queryset = queryset
|
2014-02-02 03:23:31 +08:00
|
|
|
self.limit_choices_to = limit_choices_to # limit the queryset later.
|
2008-09-02 06:43:38 +08:00
|
|
|
self.to_field_name = to_field_name
|
2007-11-13 22:36:29 +08:00
|
|
|
|
2014-11-13 04:18:11 +08:00
|
|
|
def get_limit_choices_to(self):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return ``limit_choices_to`` for this form field.
|
2014-11-13 04:18:11 +08:00
|
|
|
|
2017-01-25 05:23:56 +08:00
|
|
|
If it is a callable, invoke it and return the result.
|
2014-11-13 04:18:11 +08:00
|
|
|
"""
|
|
|
|
if callable(self.limit_choices_to):
|
|
|
|
return self.limit_choices_to()
|
|
|
|
return self.limit_choices_to
|
|
|
|
|
2010-03-09 07:55:04 +08:00
|
|
|
def __deepcopy__(self, memo):
|
|
|
|
result = super(ChoiceField, self).__deepcopy__(memo)
|
|
|
|
# Need to force a new ModelChoiceIterator to be created, bug #11183
|
2017-03-22 13:38:16 +08:00
|
|
|
if self.queryset is not None:
|
|
|
|
result.queryset = self.queryset.all()
|
2010-03-09 07:55:04 +08:00
|
|
|
return result
|
|
|
|
|
2007-11-13 22:36:29 +08:00
|
|
|
def _get_queryset(self):
|
|
|
|
return self._queryset
|
|
|
|
|
|
|
|
def _set_queryset(self, queryset):
|
2018-02-24 13:12:09 +08:00
|
|
|
self._queryset = None if queryset is None else queryset.all()
|
2007-02-21 13:14:28 +08:00
|
|
|
self.widget.choices = self.choices
|
|
|
|
|
2007-11-13 22:36:29 +08:00
|
|
|
queryset = property(_get_queryset, _set_queryset)
|
|
|
|
|
Fixed #7830 -- Removed all of the remaining, deprecated, non-oldforms features:
* Support for representing files as strings was removed. Use `django.core.files.base.ContentFile` instead.
* Support for representing uploaded files as dictionaries was removed. Use `django.core.files.uploadedfile.SimpleUploadedFile` instead.
* The `filename`, `file_name`, `file_size`, and `chuck` properties of `UploadedFile` were removed. Use the `name`, `name`, `size`, and `chunks` properties instead, respectively.
* The `get_FIELD_filename`, `get_FIELD_url`, `get_FIELD_size`, and `save_FIELD_file` methods for Models with `FileField` fields were removed. Instead, use the `path`, `url`, and `size` attributes and `save` method on the field itself, respectively.
* The `get_FIELD_width` and `get_FIELD_height` methods for Models with `ImageField` fields were removed. Use the `width` and `height` attributes on the field itself instead.
* The dispatcher `connect`, `disconnect`, `send`, and `sendExact` functions were removed. Use the signal object's own `connect`, `disconnect`, `send`, and `send` methods instead, respectively.
* The `form_for_model` and `form_for_instance` functions were removed. Use a `ModelForm` subclass instead.
* Support for importing `django.newforms` was removed. Use `django.forms` instead.
* Support for importing `django.utils.images` was removed. Use `django.core.files.images` instead.
* Support for the `follow` argument in the `create_object` and `update_object` generic views was removed. Use the `django.forms` package and the new `form_class` argument instead.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8291 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-11 05:10:47 +08:00
|
|
|
# this method will be used to create object labels by the QuerySetIterator.
|
|
|
|
# Override it to customize the label.
|
2008-03-20 07:10:45 +08:00
|
|
|
def label_from_instance(self, obj):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Convert objects into strings and generate the labels for the choices
|
|
|
|
presented by this object. Subclasses can override this method to
|
|
|
|
customize the display of the choices.
|
2008-03-20 07:10:45 +08:00
|
|
|
"""
|
2017-04-22 01:52:26 +08:00
|
|
|
return str(obj)
|
Fixed #7830 -- Removed all of the remaining, deprecated, non-oldforms features:
* Support for representing files as strings was removed. Use `django.core.files.base.ContentFile` instead.
* Support for representing uploaded files as dictionaries was removed. Use `django.core.files.uploadedfile.SimpleUploadedFile` instead.
* The `filename`, `file_name`, `file_size`, and `chuck` properties of `UploadedFile` were removed. Use the `name`, `name`, `size`, and `chunks` properties instead, respectively.
* The `get_FIELD_filename`, `get_FIELD_url`, `get_FIELD_size`, and `save_FIELD_file` methods for Models with `FileField` fields were removed. Instead, use the `path`, `url`, and `size` attributes and `save` method on the field itself, respectively.
* The `get_FIELD_width` and `get_FIELD_height` methods for Models with `ImageField` fields were removed. Use the `width` and `height` attributes on the field itself instead.
* The dispatcher `connect`, `disconnect`, `send`, and `sendExact` functions were removed. Use the signal object's own `connect`, `disconnect`, `send`, and `send` methods instead, respectively.
* The `form_for_model` and `form_for_instance` functions were removed. Use a `ModelForm` subclass instead.
* Support for importing `django.newforms` was removed. Use `django.forms` instead.
* Support for importing `django.utils.images` was removed. Use `django.core.files.images` instead.
* Support for the `follow` argument in the `create_object` and `update_object` generic views was removed. Use the `django.forms` package and the new `form_class` argument instead.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8291 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-11 05:10:47 +08:00
|
|
|
|
2007-02-21 13:14:28 +08:00
|
|
|
def _get_choices(self):
|
|
|
|
# If self._choices is set, then somebody must have manually set
|
|
|
|
# the property self.choices. In this case, just return self._choices.
|
|
|
|
if hasattr(self, '_choices'):
|
|
|
|
return self._choices
|
2008-03-20 07:10:45 +08:00
|
|
|
|
2007-02-21 13:14:28 +08:00
|
|
|
# Otherwise, execute the QuerySet in self.queryset to determine the
|
2010-08-14 20:05:41 +08:00
|
|
|
# choices dynamically. Return a fresh ModelChoiceIterator that has not been
|
|
|
|
# consumed. Note that we're instantiating a new ModelChoiceIterator *each*
|
2008-03-20 07:10:45 +08:00
|
|
|
# time _get_choices() is called (and, thus, each time self.choices is
|
|
|
|
# accessed) so that we can ensure the QuerySet has not been consumed. This
|
|
|
|
# construct might look complicated but it allows for lazy evaluation of
|
|
|
|
# the queryset.
|
2016-05-08 17:58:34 +08:00
|
|
|
return self.iterator(self)
|
2007-02-21 13:14:28 +08:00
|
|
|
|
2008-06-16 11:22:44 +08:00
|
|
|
choices = property(_get_choices, ChoiceField._set_choices)
|
2007-02-20 10:42:07 +08:00
|
|
|
|
2010-08-14 20:05:41 +08:00
|
|
|
def prepare_value(self, value):
|
|
|
|
if hasattr(value, '_meta'):
|
|
|
|
if self.to_field_name:
|
|
|
|
return value.serializable_value(self.to_field_name)
|
|
|
|
else:
|
|
|
|
return value.pk
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().prepare_value(value)
|
2010-08-14 20:05:41 +08:00
|
|
|
|
2010-01-12 22:58:24 +08:00
|
|
|
def to_python(self, value):
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2007-02-20 10:42:07 +08:00
|
|
|
return None
|
|
|
|
try:
|
2008-09-02 06:43:38 +08:00
|
|
|
key = self.to_field_name or 'pk'
|
2019-03-13 17:02:50 +08:00
|
|
|
if isinstance(value, self.queryset.model):
|
|
|
|
value = getattr(value, key)
|
2008-09-02 06:43:38 +08:00
|
|
|
value = self.queryset.get(**{key: value})
|
2014-07-26 17:06:30 +08:00
|
|
|
except (ValueError, TypeError, self.queryset.model.DoesNotExist):
|
2021-01-26 14:35:20 +08:00
|
|
|
raise ValidationError(
|
|
|
|
self.error_messages['invalid_choice'],
|
|
|
|
code='invalid_choice',
|
|
|
|
params={'value': value},
|
|
|
|
)
|
2007-02-20 10:42:07 +08:00
|
|
|
return value
|
|
|
|
|
2010-01-12 22:58:24 +08:00
|
|
|
def validate(self, value):
|
|
|
|
return Field.validate(self, value)
|
|
|
|
|
2014-08-07 10:56:23 +08:00
|
|
|
def has_changed(self, initial, data):
|
2017-07-13 22:55:32 +08:00
|
|
|
if self.disabled:
|
|
|
|
return False
|
2013-01-27 00:05:47 +08:00
|
|
|
initial_value = initial if initial is not None else ''
|
|
|
|
data_value = data if data is not None else ''
|
2017-04-22 01:52:26 +08:00
|
|
|
return str(self.prepare_value(initial_value)) != str(data_value)
|
2013-01-27 00:05:47 +08:00
|
|
|
|
2013-07-21 03:25:27 +08:00
|
|
|
|
2007-02-21 13:14:28 +08:00
|
|
|
class ModelMultipleChoiceField(ModelChoiceField):
|
2007-10-30 07:52:17 +08:00
|
|
|
"""A MultipleChoiceField whose choices are a model QuerySet."""
|
2008-08-24 01:26:00 +08:00
|
|
|
widget = SelectMultiple
|
2007-02-21 13:14:28 +08:00
|
|
|
hidden_widget = MultipleHiddenInput
|
2007-11-19 04:25:23 +08:00
|
|
|
default_error_messages = {
|
2020-03-06 05:53:16 +08:00
|
|
|
'invalid_list': _('Enter a list of values.'),
|
2013-04-14 00:20:01 +08:00
|
|
|
'invalid_choice': _('Select a valid choice. %(value)s is not one of the'
|
2012-06-08 00:08:47 +08:00
|
|
|
' available choices.'),
|
2019-06-28 00:39:47 +08:00
|
|
|
'invalid_pk_value': _('“%(pk)s” is not a valid value.')
|
2007-11-19 04:25:23 +08:00
|
|
|
}
|
2007-10-30 07:52:17 +08:00
|
|
|
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, queryset, **kwargs):
|
|
|
|
super().__init__(queryset, empty_label=None, **kwargs)
|
2007-02-20 10:42:07 +08:00
|
|
|
|
2013-12-06 21:40:51 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
if not value:
|
|
|
|
return []
|
2014-12-11 21:31:03 +08:00
|
|
|
return list(self._check_values(value))
|
2013-12-06 21:40:51 +08:00
|
|
|
|
2007-02-20 10:42:07 +08:00
|
|
|
def clean(self, value):
|
2016-07-30 22:13:10 +08:00
|
|
|
value = self.prepare_value(value)
|
2007-02-21 13:14:28 +08:00
|
|
|
if self.required and not value:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['required'], code='required')
|
2007-02-21 13:14:28 +08:00
|
|
|
elif not self.required and not value:
|
2012-10-04 00:50:12 +08:00
|
|
|
return self.queryset.none()
|
2007-02-21 13:14:28 +08:00
|
|
|
if not isinstance(value, (list, tuple)):
|
2020-03-06 05:53:16 +08:00
|
|
|
raise ValidationError(
|
|
|
|
self.error_messages['invalid_list'],
|
|
|
|
code='invalid_list',
|
|
|
|
)
|
2014-12-11 21:31:03 +08:00
|
|
|
qs = self._check_values(value)
|
|
|
|
# Since this overrides the inherited ModelChoiceField.clean
|
|
|
|
# we run custom validators here
|
|
|
|
self.run_validators(value)
|
|
|
|
return qs
|
|
|
|
|
|
|
|
def _check_values(self, value):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Given a list of possible PK values, return a QuerySet of the
|
|
|
|
corresponding objects. Raise a ValidationError if a given value is
|
2014-12-11 21:31:03 +08:00
|
|
|
invalid (not a valid PK, not in the queryset, etc.)
|
|
|
|
"""
|
2011-02-19 22:45:54 +08:00
|
|
|
key = self.to_field_name or 'pk'
|
2014-12-11 21:31:03 +08:00
|
|
|
# deduplicate given values to avoid creating many querysets or
|
|
|
|
# requiring the database backend deduplicate efficiently.
|
|
|
|
try:
|
|
|
|
value = frozenset(value)
|
|
|
|
except TypeError:
|
|
|
|
# list of lists isn't hashable, for example
|
|
|
|
raise ValidationError(
|
2020-03-06 05:53:16 +08:00
|
|
|
self.error_messages['invalid_list'],
|
|
|
|
code='invalid_list',
|
2014-12-11 21:31:03 +08:00
|
|
|
)
|
2009-04-18 23:51:11 +08:00
|
|
|
for pk in value:
|
2007-02-21 13:14:28 +08:00
|
|
|
try:
|
2011-02-19 22:45:54 +08:00
|
|
|
self.queryset.filter(**{key: pk})
|
2014-07-26 17:06:30 +08:00
|
|
|
except (ValueError, TypeError):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(
|
|
|
|
self.error_messages['invalid_pk_value'],
|
|
|
|
code='invalid_pk_value',
|
|
|
|
params={'pk': pk},
|
|
|
|
)
|
2011-02-19 22:45:54 +08:00
|
|
|
qs = self.queryset.filter(**{'%s__in' % key: value})
|
2017-06-02 07:08:59 +08:00
|
|
|
pks = {str(getattr(o, key)) for o in qs}
|
2009-04-18 23:51:11 +08:00
|
|
|
for val in value:
|
2017-04-22 01:52:26 +08:00
|
|
|
if str(val) not in pks:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(
|
|
|
|
self.error_messages['invalid_choice'],
|
|
|
|
code='invalid_choice',
|
|
|
|
params={'value': val},
|
|
|
|
)
|
2009-04-18 23:51:11 +08:00
|
|
|
return qs
|
2010-08-14 20:05:41 +08:00
|
|
|
|
|
|
|
def prepare_value(self, value):
|
2012-12-20 02:12:08 +08:00
|
|
|
if (hasattr(value, '__iter__') and
|
2016-12-29 23:27:49 +08:00
|
|
|
not isinstance(value, str) and
|
2012-12-20 02:12:08 +08:00
|
|
|
not hasattr(value, '_meta')):
|
2017-06-10 00:32:18 +08:00
|
|
|
prepare_value = super().prepare_value
|
|
|
|
return [prepare_value(v) for v in value]
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().prepare_value(value)
|
2013-01-27 00:05:47 +08:00
|
|
|
|
2014-08-07 10:56:23 +08:00
|
|
|
def has_changed(self, initial, data):
|
2017-07-13 22:55:32 +08:00
|
|
|
if self.disabled:
|
|
|
|
return False
|
2013-01-27 00:05:47 +08:00
|
|
|
if initial is None:
|
|
|
|
initial = []
|
|
|
|
if data is None:
|
|
|
|
data = []
|
|
|
|
if len(initial) != len(data):
|
|
|
|
return True
|
2017-06-02 07:08:59 +08:00
|
|
|
initial_set = {str(value) for value in self.prepare_value(initial)}
|
|
|
|
data_set = {str(value) for value in data}
|
2013-01-27 00:05:47 +08:00
|
|
|
return data_set != initial_set
|
2013-02-22 05:56:55 +08:00
|
|
|
|
|
|
|
|
|
|
|
def modelform_defines_fields(form_class):
|
2018-01-04 00:34:10 +08:00
|
|
|
return hasattr(form_class, '_meta') and (
|
|
|
|
form_class._meta.fields is not None or
|
|
|
|
form_class._meta.exclude is not None
|
|
|
|
)
|