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
|
|
|
"""
|
|
|
|
|
2008-11-01 06:07:05 +08:00
|
|
|
from django.utils.encoding import smart_unicode, force_unicode
|
2007-11-11 12:44:20 +08:00
|
|
|
from django.utils.datastructures import SortedDict
|
2008-09-02 06:22:12 +08:00
|
|
|
from django.utils.text import get_text_list, capfirst
|
2008-09-02 03:08:08 +08:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
2007-12-03 03:29:54 +08:00
|
|
|
from util import ValidationError, ErrorList
|
2008-02-14 20:56:49 +08:00
|
|
|
from forms import BaseForm, get_declared_fields
|
2008-07-19 07:54:34 +08:00
|
|
|
from fields import Field, ChoiceField, IntegerField, EMPTY_VALUES
|
|
|
|
from widgets import Select, SelectMultiple, HiddenInput, MultipleHiddenInput
|
|
|
|
from widgets import media_property
|
|
|
|
from formsets import BaseFormSet, formset_factory, DELETION_FIELD_NAME
|
2006-12-15 13:46:11 +08:00
|
|
|
|
2008-10-08 18:09:44 +08:00
|
|
|
try:
|
|
|
|
set
|
|
|
|
except NameError:
|
|
|
|
from sets import Set as set # Python 2.3 fallback
|
|
|
|
|
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',
|
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
|
|
|
'save_instance', 'form_for_fields', 'ModelChoiceField',
|
|
|
|
'ModelMultipleChoiceField',
|
2007-05-17 05:20:35 +08:00
|
|
|
)
|
2006-11-25 14:33:59 +08:00
|
|
|
|
2008-09-02 03:08:08 +08:00
|
|
|
|
2007-10-30 07:52:17 +08:00
|
|
|
def save_instance(form, instance, fields=None, fail_message='saved',
|
2008-08-31 17:49:55 +08:00
|
|
|
commit=True, exclude=None):
|
2007-01-09 13:49:47 +08:00
|
|
|
"""
|
2007-05-15 00:24:51 +08:00
|
|
|
Saves bound Form ``form``'s cleaned_data into model instance ``instance``.
|
2007-01-09 13:49:47 +08:00
|
|
|
|
2007-06-15 08:26:30 +08:00
|
|
|
If commit=True, then the changes to ``instance`` will be saved to the
|
|
|
|
database. Returns ``instance``.
|
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
|
2007-01-09 13:49:47 +08:00
|
|
|
if form.errors:
|
2007-10-30 07:52:17 +08:00
|
|
|
raise ValueError("The %s could not be %s because the data didn't"
|
|
|
|
" validate." % (opts.object_name, fail_message))
|
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) \
|
|
|
|
or not f.name in cleaned_data:
|
2007-01-09 13:49:47 +08:00
|
|
|
continue
|
2007-05-12 22:42:46 +08:00
|
|
|
if fields and f.name not in fields:
|
|
|
|
continue
|
2008-08-31 17:49:55 +08:00
|
|
|
if exclude and f.name in exclude:
|
|
|
|
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)
|
2009-03-30 23:58:52 +08:00
|
|
|
# OneToOneField doesn't allow assignment of None. Guard against that
|
|
|
|
# instead of allowing it and throwing an error.
|
|
|
|
if isinstance(f, models.OneToOneField) and cleaned_data[f.name] is None:
|
|
|
|
pass
|
2008-11-05 03:48:35 +08:00
|
|
|
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
|
|
|
|
2007-10-30 07:52:17 +08:00
|
|
|
# Wrap up the saving of m2m data as a function.
|
2007-08-05 15:39:36 +08:00
|
|
|
def save_m2m():
|
2008-07-19 07:54:34 +08:00
|
|
|
opts = instance._meta
|
2007-08-05 15:39:36 +08:00
|
|
|
cleaned_data = form.cleaned_data
|
2007-01-28 12:56:54 +08:00
|
|
|
for f in opts.many_to_many:
|
2007-05-12 22:42:46 +08:00
|
|
|
if fields and f.name not in fields:
|
|
|
|
continue
|
2007-05-15 00:24:51 +08:00
|
|
|
if f.name in cleaned_data:
|
2007-08-06 21:58:56 +08:00
|
|
|
f.save_form_data(instance, cleaned_data[f.name])
|
2007-08-05 15:39:36 +08:00
|
|
|
if commit:
|
2007-10-30 07:52:17 +08:00
|
|
|
# If we are committing, save the instance and the m2m data immediately.
|
2007-08-05 15:39:36 +08:00
|
|
|
instance.save()
|
|
|
|
save_m2m()
|
|
|
|
else:
|
2007-10-30 07:52:17 +08:00
|
|
|
# We're not committing. Add a method to the form to allow deferred
|
|
|
|
# saving of m2m data.
|
2007-08-05 15:39:36 +08:00
|
|
|
form.save_m2m = save_m2m
|
2007-01-09 13:49:47 +08:00
|
|
|
return instance
|
|
|
|
|
2007-05-12 22:42:46 +08:00
|
|
|
def make_model_save(model, fields, fail_message):
|
2007-10-30 07:52:17 +08:00
|
|
|
"""Returns the save() method for a Form."""
|
2007-01-09 13:49:47 +08:00
|
|
|
def save(self, commit=True):
|
2007-05-12 22:42:46 +08:00
|
|
|
return save_instance(self, model(), fields, fail_message, commit)
|
|
|
|
return save
|
2007-10-30 07:52:17 +08:00
|
|
|
|
2007-05-12 22:42:46 +08:00
|
|
|
def make_instance_save(instance, fields, fail_message):
|
2007-10-30 07:52:17 +08:00
|
|
|
"""Returns the save() method for a Form."""
|
2007-05-12 22:42:46 +08:00
|
|
|
def save(self, commit=True):
|
|
|
|
return save_instance(self, instance, fields, fail_message, commit)
|
2007-01-09 13:49:47 +08:00
|
|
|
return save
|
2006-12-28 10:34:53 +08:00
|
|
|
|
2006-11-25 14:33:59 +08:00
|
|
|
def form_for_fields(field_list):
|
2007-10-30 07:52:17 +08:00
|
|
|
"""
|
|
|
|
Returns a Form class for the given list of Django database field instances.
|
|
|
|
"""
|
2007-11-11 12:44:20 +08:00
|
|
|
fields = SortedDict([(f.name, f.formfield())
|
|
|
|
for f in field_list if f.editable])
|
2007-01-28 06:06:56 +08:00
|
|
|
return type('FormForFields', (BaseForm,), {'base_fields': fields})
|
2007-02-20 10:42:07 +08:00
|
|
|
|
2007-12-03 03:29:54 +08:00
|
|
|
|
|
|
|
# ModelForms #################################################################
|
|
|
|
|
|
|
|
def model_to_dict(instance, fields=None, exclude=None):
|
|
|
|
"""
|
|
|
|
Returns a dict containing the data in ``instance`` suitable for passing as
|
|
|
|
a Form's ``initial`` keyword argument.
|
2007-12-17 19:59:53 +08:00
|
|
|
|
2007-12-03 03:29:54 +08:00
|
|
|
``fields`` is an optional list of field names. If provided, only the named
|
|
|
|
fields will be included in the returned dict.
|
2007-12-17 19:59:53 +08:00
|
|
|
|
2007-12-03 03:29:54 +08:00
|
|
|
``exclude`` is an optional list of field names. If provided, the named
|
|
|
|
fields will be excluded from the returned dict, even if they are listed in
|
|
|
|
the ``fields`` argument.
|
|
|
|
"""
|
|
|
|
# avoid a circular import
|
2008-08-25 11:51:25 +08:00
|
|
|
from django.db.models.fields.related import ManyToManyField, OneToOneField
|
2007-12-03 03:29:54 +08:00
|
|
|
opts = instance._meta
|
|
|
|
data = {}
|
|
|
|
for f in opts.fields + opts.many_to_many:
|
|
|
|
if not f.editable:
|
|
|
|
continue
|
|
|
|
if fields and not f.name in fields:
|
|
|
|
continue
|
|
|
|
if exclude and f.name in exclude:
|
|
|
|
continue
|
|
|
|
if isinstance(f, ManyToManyField):
|
|
|
|
# If the object doesn't have a primry key yet, just use an empty
|
|
|
|
# list for its m2m fields. Calling f.value_from_object will raise
|
|
|
|
# an exception.
|
|
|
|
if instance.pk is None:
|
|
|
|
data[f.name] = []
|
|
|
|
else:
|
|
|
|
# MultipleChoiceWidget needs a list of pks, not object instances.
|
|
|
|
data[f.name] = [obj.pk for obj in f.value_from_object(instance)]
|
|
|
|
else:
|
|
|
|
data[f.name] = f.value_from_object(instance)
|
|
|
|
return data
|
|
|
|
|
|
|
|
def fields_for_model(model, fields=None, exclude=None, formfield_callback=lambda f: f.formfield()):
|
|
|
|
"""
|
|
|
|
Returns a ``SortedDict`` containing form fields for the given model.
|
|
|
|
|
|
|
|
``fields`` is an optional list of field names. If provided, only the named
|
|
|
|
fields will be included in the returned fields.
|
2007-12-17 19:59:53 +08:00
|
|
|
|
2007-12-03 03:29:54 +08:00
|
|
|
``exclude`` is an optional list of field names. If provided, the named
|
|
|
|
fields will be excluded from the returned fields, even if they are listed
|
|
|
|
in the ``fields`` argument.
|
|
|
|
"""
|
|
|
|
field_list = []
|
|
|
|
opts = model._meta
|
|
|
|
for f in opts.fields + opts.many_to_many:
|
|
|
|
if not f.editable:
|
|
|
|
continue
|
|
|
|
if fields and not f.name in fields:
|
|
|
|
continue
|
|
|
|
if exclude and f.name in exclude:
|
|
|
|
continue
|
|
|
|
formfield = formfield_callback(f)
|
|
|
|
if formfield:
|
|
|
|
field_list.append((f.name, formfield))
|
2009-03-15 13:05:26 +08:00
|
|
|
field_dict = SortedDict(field_list)
|
|
|
|
if fields:
|
2009-03-17 18:30:17 +08:00
|
|
|
field_dict = SortedDict([(f, field_dict.get(f)) for f in fields if (not exclude) or (exclude and f not in exclude)])
|
2009-03-15 13:05:26 +08:00
|
|
|
return field_dict
|
2007-12-03 03:29:54 +08:00
|
|
|
|
|
|
|
class ModelFormOptions(object):
|
|
|
|
def __init__(self, options=None):
|
|
|
|
self.model = getattr(options, 'model', None)
|
|
|
|
self.fields = getattr(options, 'fields', None)
|
|
|
|
self.exclude = getattr(options, 'exclude', None)
|
|
|
|
|
2008-02-14 20:56:49 +08:00
|
|
|
|
2007-12-03 03:29:54 +08:00
|
|
|
class ModelFormMetaclass(type):
|
2008-07-06 20:29:40 +08:00
|
|
|
def __new__(cls, name, bases, attrs):
|
|
|
|
formfield_callback = attrs.pop('formfield_callback',
|
|
|
|
lambda f: f.formfield())
|
2008-02-14 20:56:49 +08:00
|
|
|
try:
|
|
|
|
parents = [b for b in bases if issubclass(b, ModelForm)]
|
|
|
|
except NameError:
|
|
|
|
# We are defining ModelForm itself.
|
|
|
|
parents = None
|
2008-08-27 16:05:59 +08:00
|
|
|
declared_fields = get_declared_fields(bases, attrs, False)
|
2008-07-06 20:29:40 +08:00
|
|
|
new_class = super(ModelFormMetaclass, cls).__new__(cls, name, bases,
|
|
|
|
attrs)
|
2008-02-14 20:56:49 +08:00
|
|
|
if not parents:
|
2008-07-06 20:29:40 +08:00
|
|
|
return new_class
|
2008-02-14 20:56:49 +08:00
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
if 'media' not in attrs:
|
|
|
|
new_class.media = media_property(new_class)
|
2008-02-14 20:56:49 +08:00
|
|
|
opts = new_class._meta = ModelFormOptions(getattr(new_class, 'Meta', None))
|
|
|
|
if opts.model:
|
|
|
|
# If a model is defined, extract form fields from it.
|
|
|
|
fields = fields_for_model(opts.model, opts.fields,
|
|
|
|
opts.exclude, formfield_callback)
|
2008-02-15 17:42:50 +08:00
|
|
|
# Override default model fields with any custom declared ones
|
|
|
|
# (plus, include all the other declared fields).
|
2008-02-14 20:56:49 +08:00
|
|
|
fields.update(declared_fields)
|
|
|
|
else:
|
|
|
|
fields = declared_fields
|
2008-02-15 01:38:05 +08:00
|
|
|
new_class.declared_fields = declared_fields
|
2008-02-14 20:56:49 +08:00
|
|
|
new_class.base_fields = fields
|
|
|
|
return new_class
|
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,
|
2008-02-14 20:56:49 +08:00
|
|
|
initial=None, error_class=ErrorList, label_suffix=':',
|
2008-07-19 07:54:34 +08:00
|
|
|
empty_permitted=False, instance=None):
|
2007-12-03 03:29:54 +08:00
|
|
|
opts = self._meta
|
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)
|
2008-08-01 22:44:38 +08:00
|
|
|
super(BaseModelForm, self).__init__(data, files, auto_id, prefix, object_data,
|
|
|
|
error_class, label_suffix, empty_permitted)
|
2008-09-02 03:08:08 +08:00
|
|
|
def clean(self):
|
|
|
|
self.validate_unique()
|
|
|
|
return self.cleaned_data
|
|
|
|
|
|
|
|
def validate_unique(self):
|
2009-01-20 03:37:31 +08:00
|
|
|
from django.db.models.fields import FieldDoesNotExist, Field as ModelField
|
2008-09-02 22:20:11 +08:00
|
|
|
|
2008-12-23 13:50:51 +08:00
|
|
|
# Gather a list of checks to perform. We only perform unique checks
|
|
|
|
# for fields present and not None in cleaned_data. Since this is a
|
|
|
|
# ModelForm, some fields may have been excluded; we can't perform a unique
|
2008-10-21 22:04:24 +08:00
|
|
|
# check on a form that is missing fields involved in that check. It also does
|
2008-12-23 13:50:51 +08:00
|
|
|
# not make sense to check data that didn't validate, and since NULL does not
|
2008-10-21 22:04:24 +08:00
|
|
|
# equal NULL in SQL we should not do any unique checking for NULL values.
|
2008-09-02 22:20:11 +08:00
|
|
|
unique_checks = []
|
|
|
|
for check in self.instance._meta.unique_together[:]:
|
2008-11-06 03:47:44 +08:00
|
|
|
fields_on_form = [field for field in check if self.cleaned_data.get(field) is not None]
|
2008-09-02 22:20:11 +08:00
|
|
|
if len(fields_on_form) == len(check):
|
|
|
|
unique_checks.append(check)
|
2008-10-08 18:09:44 +08:00
|
|
|
|
2008-09-02 03:08:08 +08:00
|
|
|
form_errors = []
|
2008-10-08 18:09:44 +08:00
|
|
|
|
2008-09-02 22:20:11 +08:00
|
|
|
# Gather a list of checks for fields declared as unique and add them to
|
2008-10-21 22:04:24 +08:00
|
|
|
# the list of checks. Again, skip empty fields and any that did not validate.
|
2008-09-02 03:08:08 +08:00
|
|
|
for name, field in self.fields.items():
|
|
|
|
try:
|
|
|
|
f = self.instance._meta.get_field_by_name(name)[0]
|
|
|
|
except FieldDoesNotExist:
|
|
|
|
# This is an extra field that's not on the ModelForm, ignore it
|
|
|
|
continue
|
2009-01-20 03:37:31 +08:00
|
|
|
if not isinstance(f, ModelField):
|
2009-03-10 19:19:26 +08:00
|
|
|
# This is an extra field that happens to have a name that matches,
|
|
|
|
# for example, a related object accessor for this model. So
|
2009-01-20 03:37:31 +08:00
|
|
|
# get_field_by_name found it, but it is not a Field so do not proceed
|
|
|
|
# to use it as if it were.
|
|
|
|
continue
|
2008-11-06 03:47:44 +08:00
|
|
|
if f.unique and self.cleaned_data.get(name) is not None:
|
2008-09-02 03:08:08 +08:00
|
|
|
unique_checks.append((name,))
|
2008-10-08 18:09:44 +08:00
|
|
|
|
|
|
|
bad_fields = set()
|
2008-09-02 03:08:08 +08:00
|
|
|
for unique_check in unique_checks:
|
|
|
|
# Try to look up an existing object with the same values as this
|
|
|
|
# object's values for all the unique field.
|
2008-10-08 18:09:44 +08:00
|
|
|
|
2008-09-02 03:08:08 +08:00
|
|
|
lookup_kwargs = {}
|
|
|
|
for field_name in unique_check:
|
2009-03-30 23:58:52 +08:00
|
|
|
lookup_value = self.cleaned_data[field_name]
|
|
|
|
# ModelChoiceField will return an object instance rather than
|
|
|
|
# a raw primary key value, so convert it to a pk value before
|
|
|
|
# using it in a lookup.
|
|
|
|
if isinstance(self.fields[field_name], ModelChoiceField):
|
|
|
|
lookup_value = lookup_value.pk
|
|
|
|
lookup_kwargs[field_name] = lookup_value
|
2008-10-08 18:09:44 +08:00
|
|
|
|
2008-09-02 03:08:08 +08:00
|
|
|
qs = self.instance.__class__._default_manager.filter(**lookup_kwargs)
|
|
|
|
|
2008-10-08 18:09:44 +08:00
|
|
|
# Exclude the current object from the query if we are editing an
|
2008-09-02 03:08:08 +08:00
|
|
|
# instance (as opposed to creating a new one)
|
|
|
|
if self.instance.pk is not None:
|
|
|
|
qs = qs.exclude(pk=self.instance.pk)
|
2008-10-08 18:09:44 +08:00
|
|
|
|
2008-09-03 03:33:56 +08:00
|
|
|
# This cute trick with extra/values is the most efficient way to
|
2008-09-02 03:08:08 +08:00
|
|
|
# tell if a particular query returns any results.
|
|
|
|
if qs.extra(select={'a': 1}).values('a').order_by():
|
2008-09-02 06:22:12 +08:00
|
|
|
model_name = capfirst(self.instance._meta.verbose_name)
|
2008-10-08 18:09:44 +08:00
|
|
|
|
2008-09-02 03:08:08 +08:00
|
|
|
# A unique field
|
|
|
|
if len(unique_check) == 1:
|
|
|
|
field_name = unique_check[0]
|
|
|
|
field_label = self.fields[field_name].label
|
|
|
|
# Insert the error into the error dict, very sneaky
|
|
|
|
self._errors[field_name] = ErrorList([
|
2008-09-02 06:32:40 +08:00
|
|
|
_(u"%(model_name)s with this %(field_label)s already exists.") % \
|
|
|
|
{'model_name': unicode(model_name),
|
|
|
|
'field_label': unicode(field_label)}
|
2008-09-02 03:08:08 +08:00
|
|
|
])
|
|
|
|
# unique_together
|
|
|
|
else:
|
|
|
|
field_labels = [self.fields[field_name].label for field_name in unique_check]
|
|
|
|
field_labels = get_text_list(field_labels, _('and'))
|
|
|
|
form_errors.append(
|
2008-09-02 06:32:40 +08:00
|
|
|
_(u"%(model_name)s with this %(field_label)s already exists.") % \
|
|
|
|
{'model_name': unicode(model_name),
|
|
|
|
'field_label': unicode(field_labels)}
|
2008-09-02 03:08:08 +08:00
|
|
|
)
|
2008-10-08 18:09:44 +08:00
|
|
|
|
|
|
|
# Mark these fields as needing to be removed from cleaned data
|
|
|
|
# later.
|
2008-09-02 03:08:08 +08:00
|
|
|
for field_name in unique_check:
|
2008-10-08 18:09:44 +08:00
|
|
|
bad_fields.add(field_name)
|
|
|
|
|
|
|
|
for field_name in bad_fields:
|
|
|
|
del self.cleaned_data[field_name]
|
2008-09-02 03:08:08 +08:00
|
|
|
if form_errors:
|
2008-10-08 18:09:44 +08:00
|
|
|
# Raise the unique together errors since they are considered
|
|
|
|
# form-wide.
|
2008-09-02 03:08:08 +08:00
|
|
|
raise ValidationError(form_errors)
|
2007-12-03 03:29:54 +08:00
|
|
|
|
|
|
|
def save(self, commit=True):
|
|
|
|
"""
|
2008-02-14 20:56:49 +08:00
|
|
|
Saves this ``form``'s cleaned_data into model instance
|
|
|
|
``self.instance``.
|
2007-12-03 03:29:54 +08:00
|
|
|
|
|
|
|
If commit=True, then the changes to ``instance`` will be saved to the
|
|
|
|
database. Returns ``instance``.
|
|
|
|
"""
|
|
|
|
if self.instance.pk is None:
|
|
|
|
fail_message = 'created'
|
|
|
|
else:
|
|
|
|
fail_message = 'changed'
|
|
|
|
return save_instance(self, self.instance, self._meta.fields, fail_message, commit)
|
|
|
|
|
2008-12-23 13:50:51 +08:00
|
|
|
save.alters_data = True
|
|
|
|
|
2007-12-03 03:29:54 +08:00
|
|
|
class ModelForm(BaseModelForm):
|
|
|
|
__metaclass__ = ModelFormMetaclass
|
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def modelform_factory(model, form=ModelForm, fields=None, exclude=None,
|
|
|
|
formfield_callback=lambda f: f.formfield()):
|
|
|
|
# HACK: we should be able to construct a ModelForm without creating
|
|
|
|
# and passing in a temporary inner class
|
|
|
|
class Meta:
|
|
|
|
pass
|
|
|
|
setattr(Meta, 'model', model)
|
|
|
|
setattr(Meta, 'fields', fields)
|
|
|
|
setattr(Meta, 'exclude', exclude)
|
|
|
|
class_name = model.__name__ + 'Form'
|
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
|
|
|
return ModelFormMetaclass(class_name, (form,), {'Meta': Meta,
|
2008-07-19 07:54:34 +08:00
|
|
|
'formfield_callback': formfield_callback})
|
|
|
|
|
|
|
|
|
|
|
|
# ModelFormSets ##############################################################
|
|
|
|
|
|
|
|
class BaseModelFormSet(BaseFormSet):
|
|
|
|
"""
|
|
|
|
A ``FormSet`` for editing a queryset and/or adding new objects to it.
|
|
|
|
"""
|
|
|
|
model = None
|
|
|
|
|
|
|
|
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
|
|
|
|
queryset=None, **kwargs):
|
|
|
|
self.queryset = queryset
|
|
|
|
defaults = {'data': data, 'files': files, 'auto_id': auto_id, 'prefix': prefix}
|
|
|
|
defaults.update(kwargs)
|
|
|
|
super(BaseModelFormSet, self).__init__(**defaults)
|
|
|
|
|
2009-03-30 23:58:52 +08:00
|
|
|
def initial_form_count(self):
|
|
|
|
"""Returns the number of forms that are required in this FormSet."""
|
|
|
|
if not (self.data or self.files):
|
|
|
|
return len(self.get_queryset())
|
|
|
|
return super(BaseModelFormSet, self).initial_form_count()
|
|
|
|
|
2008-09-02 03:08:08 +08:00
|
|
|
def _construct_form(self, i, **kwargs):
|
2009-03-30 23:58:52 +08:00
|
|
|
if i < self.initial_form_count():
|
2008-09-02 03:08:08 +08:00
|
|
|
kwargs['instance'] = self.get_queryset()[i]
|
|
|
|
return super(BaseModelFormSet, self)._construct_form(i, **kwargs)
|
|
|
|
|
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:
|
|
|
|
qs = self.model._default_manager.get_query_set()
|
|
|
|
if self.max_num > 0:
|
|
|
|
self._queryset = qs[:self.max_num]
|
|
|
|
else:
|
|
|
|
self._queryset = qs
|
|
|
|
return self._queryset
|
2008-07-19 07:54:34 +08:00
|
|
|
|
|
|
|
def save_new(self, form, commit=True):
|
|
|
|
"""Saves and returns 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):
|
|
|
|
"""Saves and returns 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
|
|
|
|
|
|
|
def save(self, commit=True):
|
|
|
|
"""Saves model instances for every form, adding and changing instances
|
|
|
|
as necessary, and returns the list of instances.
|
|
|
|
"""
|
|
|
|
if not commit:
|
|
|
|
self.saved_forms = []
|
|
|
|
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)
|
|
|
|
|
|
|
|
def save_existing_objects(self, commit=True):
|
|
|
|
self.changed_objects = []
|
|
|
|
self.deleted_objects = []
|
|
|
|
if not self.get_queryset():
|
|
|
|
return []
|
|
|
|
|
|
|
|
# Put the objects from self.get_queryset into a dict so they are easy to lookup by pk
|
|
|
|
existing_objects = {}
|
|
|
|
for obj in self.get_queryset():
|
|
|
|
existing_objects[obj.pk] = obj
|
|
|
|
saved_instances = []
|
|
|
|
for form in self.initial_forms:
|
2009-04-01 03:55:20 +08:00
|
|
|
pk_name = self._pk_field.name
|
|
|
|
raw_pk_value = form._raw_value(pk_name)
|
|
|
|
pk_value = form.fields[pk_name].clean(raw_pk_value).pk
|
|
|
|
obj = existing_objects[pk_value]
|
|
|
|
if self.can_delete:
|
|
|
|
raw_delete_value = form._raw_value(DELETION_FIELD_NAME)
|
|
|
|
should_delete = form.fields[DELETION_FIELD_NAME].clean(raw_delete_value)
|
|
|
|
if should_delete:
|
|
|
|
self.deleted_objects.append(obj)
|
|
|
|
obj.delete()
|
|
|
|
continue
|
|
|
|
if form.changed_data:
|
|
|
|
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.
|
2009-04-01 03:55:20 +08:00
|
|
|
if self.can_delete:
|
|
|
|
raw_delete_value = form._raw_value(DELETION_FIELD_NAME)
|
|
|
|
should_delete = form.fields[DELETION_FIELD_NAME].clean(raw_delete_value)
|
|
|
|
if should_delete:
|
|
|
|
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."""
|
2009-03-30 23:58:52 +08:00
|
|
|
from django.db.models import AutoField, OneToOneField, ForeignKey
|
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.
|
|
|
|
if (not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)):
|
|
|
|
try:
|
|
|
|
pk_value = self.get_queryset()[index].pk
|
|
|
|
except IndexError:
|
|
|
|
pk_value = None
|
|
|
|
if isinstance(pk, OneToOneField) or isinstance(pk, ForeignKey):
|
|
|
|
qs = pk.rel.to._default_manager.get_query_set()
|
|
|
|
else:
|
|
|
|
qs = self.model._default_manager.get_query_set()
|
|
|
|
form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_value, required=False, widget=HiddenInput)
|
2008-07-19 07:54:34 +08:00
|
|
|
super(BaseModelFormSet, self).add_fields(form, index)
|
|
|
|
|
|
|
|
def modelformset_factory(model, form=ModelForm, formfield_callback=lambda f: f.formfield(),
|
|
|
|
formset=BaseModelFormSet,
|
|
|
|
extra=1, can_delete=False, can_order=False,
|
|
|
|
max_num=0, fields=None, exclude=None):
|
|
|
|
"""
|
|
|
|
Returns a FormSet class for the given Django model class.
|
|
|
|
"""
|
|
|
|
form = modelform_factory(model, form=form, fields=fields, exclude=exclude,
|
|
|
|
formfield_callback=formfield_callback)
|
|
|
|
FormSet = formset_factory(form, formset, extra=extra, max_num=max_num,
|
|
|
|
can_order=can_order, can_delete=can_delete)
|
|
|
|
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,
|
|
|
|
save_as_new=False, prefix=None):
|
2008-07-19 07:54:34 +08:00
|
|
|
from django.db.models.fields.related import RelatedObject
|
2008-10-29 04:01:03 +08:00
|
|
|
if instance is None:
|
|
|
|
self.instance = self.model()
|
|
|
|
else:
|
|
|
|
self.instance = instance
|
2008-07-19 07:54:34 +08:00
|
|
|
self.save_as_new = save_as_new
|
|
|
|
# is there a better way to get the object descriptor?
|
|
|
|
self.rel_name = RelatedObject(self.fk.rel.to, self.model, self.fk).get_accessor_name()
|
2008-11-14 23:37:59 +08:00
|
|
|
qs = self.model._default_manager.filter(**{self.fk.name: self.instance})
|
2009-03-10 19:19:26 +08:00
|
|
|
super(BaseInlineFormSet, self).__init__(data, files, prefix=prefix,
|
2008-11-14 23:37:59 +08:00
|
|
|
queryset=qs)
|
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
|
|
|
|
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
|
|
|
|
return super(BaseInlineFormSet, self).initial_form_count()
|
|
|
|
|
|
|
|
def total_form_count(self):
|
|
|
|
if self.save_as_new:
|
|
|
|
return super(BaseInlineFormSet, self).initial_form_count()
|
|
|
|
return super(BaseInlineFormSet, self).total_form_count()
|
2008-07-19 07:54:34 +08:00
|
|
|
|
2008-09-02 03:08:08 +08:00
|
|
|
def _construct_form(self, i, **kwargs):
|
|
|
|
form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs)
|
|
|
|
if self.save_as_new:
|
|
|
|
# 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
|
2008-09-02 03:08:08 +08:00
|
|
|
return form
|
2008-12-23 13:50:51 +08:00
|
|
|
|
2009-03-10 19:19:26 +08:00
|
|
|
#@classmethod
|
|
|
|
def get_default_prefix(cls):
|
|
|
|
from django.db.models.fields.related import RelatedObject
|
|
|
|
return RelatedObject(cls.fk.rel.to, cls.model, cls.fk).get_accessor_name()
|
|
|
|
get_default_prefix = classmethod(get_default_prefix)
|
|
|
|
|
2008-07-19 07:54:34 +08:00
|
|
|
def save_new(self, form, commit=True):
|
2009-03-30 23:58:52 +08:00
|
|
|
# Use commit=False so we can assign the parent key afterwards, then
|
|
|
|
# save the object.
|
|
|
|
obj = form.save(commit=False)
|
|
|
|
setattr(obj, self.fk.get_attname(), self.instance.pk)
|
|
|
|
obj.save()
|
|
|
|
# form.save_m2m() can be called via the formset later on if commit=False
|
|
|
|
if commit and hasattr(form, 'save_m2m'):
|
|
|
|
form.save_m2m()
|
|
|
|
return obj
|
2008-10-08 18:09:44 +08:00
|
|
|
|
2008-08-31 17:49:55 +08:00
|
|
|
def add_fields(self, form, index):
|
|
|
|
super(BaseInlineFormSet, self).add_fields(form, index)
|
|
|
|
if self._pk_field == self.fk:
|
2008-11-01 06:07:05 +08:00
|
|
|
form.fields[self._pk_field.name] = InlineForeignKeyField(self.instance, pk_field=True)
|
|
|
|
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.
|
|
|
|
form.fields[self.fk.name] = InlineForeignKeyField(self.instance,
|
|
|
|
label=getattr(form.fields.get(self.fk.name), 'label', capfirst(self.fk.verbose_name))
|
|
|
|
)
|
2008-07-19 07:54:34 +08:00
|
|
|
|
|
|
|
def _get_foreign_key(parent_model, model, fk_name=None):
|
|
|
|
"""
|
|
|
|
Finds and returns the ForeignKey from model to parent if there is one.
|
|
|
|
If fk_name is provided, assume it is the name of the ForeignKey field.
|
|
|
|
"""
|
|
|
|
# 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 \
|
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
|
|
|
(fk.rel.to != parent_model and
|
2008-08-30 01:41:40 +08:00
|
|
|
fk.rel.to not in parent_model._meta.get_parent_list()):
|
2008-07-19 07:54:34 +08:00
|
|
|
raise Exception("fk_name '%s' is not a ForeignKey to %s" % (fk_name, parent_model))
|
|
|
|
elif len(fks_to_parent) == 0:
|
|
|
|
raise Exception("%s has no field named '%s'" % (model, fk_name))
|
|
|
|
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
|
|
|
|
if isinstance(f, ForeignKey)
|
|
|
|
and (f.rel.to == parent_model
|
2008-08-30 01:41:40 +08:00
|
|
|
or f.rel.to 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]
|
|
|
|
elif len(fks_to_parent) == 0:
|
|
|
|
raise Exception("%s has no ForeignKey to %s" % (model, parent_model))
|
|
|
|
else:
|
|
|
|
raise Exception("%s has more than 1 ForeignKey to %s" % (model, parent_model))
|
|
|
|
return fk
|
|
|
|
|
|
|
|
|
|
|
|
def inlineformset_factory(parent_model, model, form=ModelForm,
|
2008-08-09 04:27:48 +08:00
|
|
|
formset=BaseInlineFormSet, fk_name=None,
|
2008-07-19 07:54:34 +08:00
|
|
|
fields=None, exclude=None,
|
|
|
|
extra=3, can_order=False, can_delete=True, max_num=0,
|
|
|
|
formfield_callback=lambda f: f.formfield()):
|
|
|
|
"""
|
2008-08-09 04:27:48 +08:00
|
|
|
Returns an ``InlineFormSet`` for the given kwargs.
|
2008-07-19 07:54:34 +08:00
|
|
|
|
|
|
|
You must provide ``fk_name`` if ``model`` has more than one ``ForeignKey``
|
|
|
|
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
|
2008-11-02 06:25:41 +08:00
|
|
|
if fields is not None:
|
|
|
|
fields = list(fields)
|
|
|
|
fields.append(fk.name)
|
|
|
|
else:
|
|
|
|
# get all the fields for this model that will be generated.
|
|
|
|
fields = fields_for_model(model, fields, exclude, formfield_callback).keys()
|
|
|
|
fields.append(fk.name)
|
2008-09-01 05:14:46 +08:00
|
|
|
kwargs = {
|
|
|
|
'form': form,
|
|
|
|
'formfield_callback': formfield_callback,
|
|
|
|
'formset': formset,
|
|
|
|
'extra': extra,
|
|
|
|
'can_delete': can_delete,
|
|
|
|
'can_order': can_order,
|
|
|
|
'fields': fields,
|
|
|
|
'exclude': exclude,
|
|
|
|
'max_num': max_num,
|
|
|
|
}
|
|
|
|
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 InlineForeignKeyHiddenInput(HiddenInput):
|
|
|
|
def _has_changed(self, initial, data):
|
|
|
|
return False
|
|
|
|
|
|
|
|
class InlineForeignKeyField(Field):
|
|
|
|
"""
|
|
|
|
A basic integer field that deals with validating the given value to a
|
|
|
|
given parent instance in an inline.
|
|
|
|
"""
|
|
|
|
default_error_messages = {
|
|
|
|
'invalid_choice': _(u'The inline foreign key did not match the parent instance primary key.'),
|
|
|
|
}
|
2008-12-23 13:50:51 +08:00
|
|
|
|
2008-11-01 06:07:05 +08:00
|
|
|
def __init__(self, parent_instance, *args, **kwargs):
|
|
|
|
self.parent_instance = parent_instance
|
|
|
|
self.pk_field = kwargs.pop("pk_field", False)
|
|
|
|
if self.parent_instance is not None:
|
|
|
|
kwargs["initial"] = self.parent_instance.pk
|
|
|
|
kwargs["required"] = False
|
|
|
|
kwargs["widget"] = InlineForeignKeyHiddenInput
|
|
|
|
super(InlineForeignKeyField, self).__init__(*args, **kwargs)
|
2008-12-23 13:50:51 +08:00
|
|
|
|
2008-11-01 06:07:05 +08:00
|
|
|
def clean(self, value):
|
|
|
|
if value in EMPTY_VALUES:
|
|
|
|
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.
|
|
|
|
if force_unicode(value) != force_unicode(self.parent_instance.pk):
|
|
|
|
raise ValidationError(self.error_messages['invalid_choice'])
|
|
|
|
return self.parent_instance
|
|
|
|
|
2008-03-20 07:10:45 +08:00
|
|
|
class ModelChoiceIterator(object):
|
|
|
|
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:
|
|
|
|
yield (u"", self.field.empty_label)
|
2008-06-20 05:15:33 +08:00
|
|
|
if self.field.cache_choices:
|
|
|
|
if self.field.choice_cache is None:
|
|
|
|
self.field.choice_cache = [
|
2008-09-02 06:43:38 +08:00
|
|
|
self.choice(obj) for obj in self.queryset.all()
|
2008-06-20 05:15:33 +08:00
|
|
|
]
|
|
|
|
for choice in self.field.choice_cache:
|
|
|
|
yield choice
|
|
|
|
else:
|
|
|
|
for obj in self.queryset.all():
|
2008-09-02 06:43:38 +08:00
|
|
|
yield self.choice(obj)
|
|
|
|
|
|
|
|
def choice(self, obj):
|
|
|
|
if self.field.to_field_name:
|
2008-12-08 16:15:37 +08:00
|
|
|
key = obj.serializable_value(self.field.to_field_name)
|
2008-09-02 06:43:38 +08:00
|
|
|
else:
|
|
|
|
key = obj.pk
|
|
|
|
return (key, self.field.label_from_instance(obj))
|
|
|
|
|
2007-02-21 13:14:28 +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 = {
|
|
|
|
'invalid_choice': _(u'Select a valid choice. That choice is not one of'
|
|
|
|
u' the available choices.'),
|
|
|
|
}
|
2007-10-30 07:52:17 +08:00
|
|
|
|
2007-02-21 13:14:28 +08:00
|
|
|
def __init__(self, queryset, empty_label=u"---------", cache_choices=False,
|
2008-08-24 01:26:00 +08:00
|
|
|
required=True, widget=None, label=None, initial=None,
|
2008-09-02 06:43:38 +08:00
|
|
|
help_text=None, to_field_name=None, *args, **kwargs):
|
2007-02-21 13:14:28 +08:00
|
|
|
self.empty_label = empty_label
|
|
|
|
self.cache_choices = cache_choices
|
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
|
|
|
# Call Field instead of ChoiceField __init__() because we don't need
|
|
|
|
# ChoiceField.__init__().
|
2007-11-19 04:25:23 +08:00
|
|
|
Field.__init__(self, required, widget, label, initial, help_text,
|
|
|
|
*args, **kwargs)
|
2007-11-13 22:36:29 +08:00
|
|
|
self.queryset = queryset
|
2008-06-20 05:15:33 +08:00
|
|
|
self.choice_cache = None
|
2008-09-02 06:43:38 +08:00
|
|
|
self.to_field_name = to_field_name
|
2007-11-13 22:36:29 +08:00
|
|
|
|
|
|
|
def _get_queryset(self):
|
|
|
|
return self._queryset
|
|
|
|
|
|
|
|
def _set_queryset(self, queryset):
|
|
|
|
self._queryset = queryset
|
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):
|
|
|
|
"""
|
|
|
|
This method is used to convert objects into strings; it's used to
|
|
|
|
generate the labels for the choices presented by this object. Subclasses
|
|
|
|
can override this method to customize the display of the choices.
|
|
|
|
"""
|
|
|
|
return smart_unicode(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
|
2008-03-20 07:10:45 +08:00
|
|
|
# choices dynamically. Return a fresh QuerySetIterator that has not been
|
|
|
|
# consumed. Note that we're instantiating a new QuerySetIterator *each*
|
|
|
|
# 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.
|
|
|
|
return ModelChoiceIterator(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
|
|
|
|
|
|
|
def clean(self, value):
|
2007-02-21 13:14:28 +08:00
|
|
|
Field.clean(self, value)
|
2007-11-19 12:07:03 +08:00
|
|
|
if value in 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'
|
|
|
|
value = self.queryset.get(**{key: value})
|
2007-02-21 13:14:28 +08:00
|
|
|
except self.queryset.model.DoesNotExist:
|
2007-11-19 04:25:23 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid_choice'])
|
2007-02-20 10:42:07 +08:00
|
|
|
return value
|
|
|
|
|
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 = {
|
|
|
|
'list': _(u'Enter a list of values.'),
|
|
|
|
'invalid_choice': _(u'Select a valid choice. %s is not one of the'
|
|
|
|
u' available choices.'),
|
2009-03-31 07:00:36 +08:00
|
|
|
'invalid_pk_value': _(u'"%s" is not a valid value for a primary key.')
|
2007-11-19 04:25:23 +08:00
|
|
|
}
|
2007-10-30 07:52:17 +08:00
|
|
|
|
2007-02-21 13:14:28 +08:00
|
|
|
def __init__(self, queryset, cache_choices=False, required=True,
|
2008-08-24 01:26:00 +08:00
|
|
|
widget=None, label=None, initial=None,
|
2007-11-19 04:25:23 +08:00
|
|
|
help_text=None, *args, **kwargs):
|
2007-10-30 07:52:17 +08:00
|
|
|
super(ModelMultipleChoiceField, self).__init__(queryset, None,
|
2007-11-19 04:25:23 +08:00
|
|
|
cache_choices, required, widget, label, initial, help_text,
|
|
|
|
*args, **kwargs)
|
2007-02-20 10:42:07 +08:00
|
|
|
|
|
|
|
def clean(self, value):
|
2007-02-21 13:14:28 +08:00
|
|
|
if self.required and not value:
|
2007-11-19 04:25:23 +08:00
|
|
|
raise ValidationError(self.error_messages['required'])
|
2007-02-21 13:14:28 +08:00
|
|
|
elif not self.required and not value:
|
2007-02-20 10:42:07 +08:00
|
|
|
return []
|
2007-02-21 13:14:28 +08:00
|
|
|
if not isinstance(value, (list, tuple)):
|
2007-11-19 04:25:23 +08:00
|
|
|
raise ValidationError(self.error_messages['list'])
|
2007-02-21 13:14:28 +08:00
|
|
|
final_values = []
|
|
|
|
for val in value:
|
|
|
|
try:
|
2007-11-13 22:36:29 +08:00
|
|
|
obj = self.queryset.get(pk=val)
|
2007-02-21 13:14:28 +08:00
|
|
|
except self.queryset.model.DoesNotExist:
|
2007-11-19 04:25:23 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid_choice'] % val)
|
2009-03-31 07:00:36 +08:00
|
|
|
except ValueError:
|
|
|
|
raise ValidationError(self.error_messages['invalid_pk_value'] % val)
|
2007-02-21 13:14:28 +08:00
|
|
|
else:
|
|
|
|
final_values.append(obj)
|
|
|
|
return final_values
|