OLD | NEW |
(Empty) | |
| 1 """ |
| 2 Helper functions for creating Form classes from Django models |
| 3 and database field objects. |
| 4 """ |
| 5 |
| 6 from __future__ import unicode_literals |
| 7 |
| 8 from collections import OrderedDict |
| 9 from itertools import chain |
| 10 |
| 11 from django.core.exceptions import ( |
| 12 NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError, |
| 13 ) |
| 14 from django.forms.fields import ChoiceField, Field |
| 15 from django.forms.forms import BaseForm, DeclarativeFieldsMetaclass |
| 16 from django.forms.formsets import BaseFormSet, formset_factory |
| 17 from django.forms.utils import ErrorList |
| 18 from django.forms.widgets import ( |
| 19 HiddenInput, MultipleHiddenInput, SelectMultiple, |
| 20 ) |
| 21 from django.utils import six |
| 22 from django.utils.encoding import force_text |
| 23 from django.utils.text import capfirst, get_text_list |
| 24 from django.utils.translation import ugettext, ugettext_lazy as _ |
| 25 |
| 26 __all__ = ( |
| 27 'ModelForm', 'BaseModelForm', 'model_to_dict', 'fields_for_model', |
| 28 'ModelChoiceField', 'ModelMultipleChoiceField', 'ALL_FIELDS', |
| 29 'BaseModelFormSet', 'modelformset_factory', 'BaseInlineFormSet', |
| 30 'inlineformset_factory', 'modelform_factory', |
| 31 ) |
| 32 |
| 33 ALL_FIELDS = '__all__' |
| 34 |
| 35 |
| 36 def construct_instance(form, instance, fields=None, exclude=None): |
| 37 """ |
| 38 Constructs and returns a model instance from the bound ``form``'s |
| 39 ``cleaned_data``, but does not save the returned instance to the |
| 40 database. |
| 41 """ |
| 42 from django.db import models |
| 43 opts = instance._meta |
| 44 |
| 45 cleaned_data = form.cleaned_data |
| 46 file_field_list = [] |
| 47 for f in opts.fields: |
| 48 if not f.editable or isinstance(f, models.AutoField) \ |
| 49 or f.name not in cleaned_data: |
| 50 continue |
| 51 if fields is not None and f.name not in fields: |
| 52 continue |
| 53 if exclude and f.name in exclude: |
| 54 continue |
| 55 # Leave defaults for fields that aren't in POST data, except for |
| 56 # checkbox inputs because they don't appear in POST data if not checked. |
| 57 if (f.has_default() and |
| 58 form[f.name].field.widget.value_omitted_from_data(form.data, for
m.files, form.add_prefix(f.name))): |
| 59 continue |
| 60 # Defer saving file-type fields until after the other fields, so a |
| 61 # callable upload_to can use the values from other fields. |
| 62 if isinstance(f, models.FileField): |
| 63 file_field_list.append(f) |
| 64 else: |
| 65 f.save_form_data(instance, cleaned_data[f.name]) |
| 66 |
| 67 for f in file_field_list: |
| 68 f.save_form_data(instance, cleaned_data[f.name]) |
| 69 |
| 70 return instance |
| 71 |
| 72 |
| 73 # ModelForms ################################################################# |
| 74 |
| 75 def model_to_dict(instance, fields=None, exclude=None): |
| 76 """ |
| 77 Returns a dict containing the data in ``instance`` suitable for passing as |
| 78 a Form's ``initial`` keyword argument. |
| 79 |
| 80 ``fields`` is an optional list of field names. If provided, only the named |
| 81 fields will be included in the returned dict. |
| 82 |
| 83 ``exclude`` is an optional list of field names. If provided, the named |
| 84 fields will be excluded from the returned dict, even if they are listed in |
| 85 the ``fields`` argument. |
| 86 """ |
| 87 from django.db import models |
| 88 opts = instance._meta |
| 89 data = {} |
| 90 for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many)
: |
| 91 if not getattr(f, 'editable', False): |
| 92 continue |
| 93 if fields and f.name not in fields: |
| 94 continue |
| 95 if exclude and f.name in exclude: |
| 96 continue |
| 97 data[f.name] = f.value_from_object(instance) |
| 98 # Evaluate ManyToManyField QuerySets to prevent subsequent model |
| 99 # alteration of that field from being reflected in the data. |
| 100 if isinstance(f, models.ManyToManyField): |
| 101 data[f.name] = list(data[f.name]) |
| 102 return data |
| 103 |
| 104 |
| 105 def apply_limit_choices_to_to_formfield(formfield): |
| 106 """Apply limit_choices_to to the formfield's queryset if needed.""" |
| 107 if hasattr(formfield, 'queryset') and hasattr(formfield, 'get_limit_choices_
to'): |
| 108 limit_choices_to = formfield.get_limit_choices_to() |
| 109 if limit_choices_to is not None: |
| 110 formfield.queryset = formfield.queryset.complex_filter(limit_choices
_to) |
| 111 |
| 112 |
| 113 def fields_for_model(model, fields=None, exclude=None, widgets=None, |
| 114 formfield_callback=None, localized_fields=None, |
| 115 labels=None, help_texts=None, error_messages=None, |
| 116 field_classes=None, apply_limit_choices_to=True): |
| 117 """ |
| 118 Returns a ``OrderedDict`` containing form fields for the given model. |
| 119 |
| 120 ``fields`` is an optional list of field names. If provided, only the named |
| 121 fields will be included in the returned fields. |
| 122 |
| 123 ``exclude`` is an optional list of field names. If provided, the named |
| 124 fields will be excluded from the returned fields, even if they are listed |
| 125 in the ``fields`` argument. |
| 126 |
| 127 ``widgets`` is a dictionary of model field names mapped to a widget. |
| 128 |
| 129 ``formfield_callback`` is a callable that takes a model field and returns |
| 130 a form field. |
| 131 |
| 132 ``localized_fields`` is a list of names of fields which should be localized. |
| 133 |
| 134 ``labels`` is a dictionary of model field names mapped to a label. |
| 135 |
| 136 ``help_texts`` is a dictionary of model field names mapped to a help text. |
| 137 |
| 138 ``error_messages`` is a dictionary of model field names mapped to a |
| 139 dictionary of error messages. |
| 140 |
| 141 ``field_classes`` is a dictionary of model field names mapped to a form |
| 142 field class. |
| 143 |
| 144 ``apply_limit_choices_to`` is a boolean indicating if limit_choices_to |
| 145 should be applied to a field's queryset. |
| 146 """ |
| 147 field_list = [] |
| 148 ignored = [] |
| 149 opts = model._meta |
| 150 # Avoid circular import |
| 151 from django.db.models.fields import Field as ModelField |
| 152 sortable_private_fields = [f for f in opts.private_fields if isinstance(f, M
odelField)] |
| 153 for f in sorted(chain(opts.concrete_fields, sortable_private_fields, opts.ma
ny_to_many)): |
| 154 if not getattr(f, 'editable', False): |
| 155 if (fields is not None and f.name in fields and |
| 156 (exclude is None or f.name not in exclude)): |
| 157 raise FieldError( |
| 158 "'%s' cannot be specified for %s model form as it is a non-e
ditable field" % ( |
| 159 f.name, model.__name__) |
| 160 ) |
| 161 continue |
| 162 if fields is not None and f.name not in fields: |
| 163 continue |
| 164 if exclude and f.name in exclude: |
| 165 continue |
| 166 |
| 167 kwargs = {} |
| 168 if widgets and f.name in widgets: |
| 169 kwargs['widget'] = widgets[f.name] |
| 170 if localized_fields == ALL_FIELDS or (localized_fields and f.name in loc
alized_fields): |
| 171 kwargs['localize'] = True |
| 172 if labels and f.name in labels: |
| 173 kwargs['label'] = labels[f.name] |
| 174 if help_texts and f.name in help_texts: |
| 175 kwargs['help_text'] = help_texts[f.name] |
| 176 if error_messages and f.name in error_messages: |
| 177 kwargs['error_messages'] = error_messages[f.name] |
| 178 if field_classes and f.name in field_classes: |
| 179 kwargs['form_class'] = field_classes[f.name] |
| 180 |
| 181 if formfield_callback is None: |
| 182 formfield = f.formfield(**kwargs) |
| 183 elif not callable(formfield_callback): |
| 184 raise TypeError('formfield_callback must be a function or callable') |
| 185 else: |
| 186 formfield = formfield_callback(f, **kwargs) |
| 187 |
| 188 if formfield: |
| 189 if apply_limit_choices_to: |
| 190 apply_limit_choices_to_to_formfield(formfield) |
| 191 field_list.append((f.name, formfield)) |
| 192 else: |
| 193 ignored.append(f.name) |
| 194 field_dict = OrderedDict(field_list) |
| 195 if fields: |
| 196 field_dict = OrderedDict( |
| 197 [(f, field_dict.get(f)) for f in fields |
| 198 if ((not exclude) or (exclude and f not in exclude)) and (f not
in ignored)] |
| 199 ) |
| 200 return field_dict |
| 201 |
| 202 |
| 203 class ModelFormOptions(object): |
| 204 def __init__(self, options=None): |
| 205 self.model = getattr(options, 'model', None) |
| 206 self.fields = getattr(options, 'fields', None) |
| 207 self.exclude = getattr(options, 'exclude', None) |
| 208 self.widgets = getattr(options, 'widgets', None) |
| 209 self.localized_fields = getattr(options, 'localized_fields', None) |
| 210 self.labels = getattr(options, 'labels', None) |
| 211 self.help_texts = getattr(options, 'help_texts', None) |
| 212 self.error_messages = getattr(options, 'error_messages', None) |
| 213 self.field_classes = getattr(options, 'field_classes', None) |
| 214 |
| 215 |
| 216 class ModelFormMetaclass(DeclarativeFieldsMetaclass): |
| 217 def __new__(mcs, name, bases, attrs): |
| 218 base_formfield_callback = None |
| 219 for b in bases: |
| 220 if hasattr(b, 'Meta') and hasattr(b.Meta, 'formfield_callback'): |
| 221 base_formfield_callback = b.Meta.formfield_callback |
| 222 break |
| 223 |
| 224 formfield_callback = attrs.pop('formfield_callback', base_formfield_call
back) |
| 225 |
| 226 new_class = super(ModelFormMetaclass, mcs).__new__(mcs, name, bases, att
rs) |
| 227 |
| 228 if bases == (BaseModelForm,): |
| 229 return new_class |
| 230 |
| 231 opts = new_class._meta = ModelFormOptions(getattr(new_class, 'Meta', Non
e)) |
| 232 |
| 233 # We check if a string was passed to `fields` or `exclude`, |
| 234 # which is likely to be a mistake where the user typed ('foo') instead |
| 235 # of ('foo',) |
| 236 for opt in ['fields', 'exclude', 'localized_fields']: |
| 237 value = getattr(opts, opt) |
| 238 if isinstance(value, six.string_types) and value != ALL_FIELDS: |
| 239 msg = ("%(model)s.Meta.%(opt)s cannot be a string. " |
| 240 "Did you mean to type: ('%(value)s',)?" % { |
| 241 'model': new_class.__name__, |
| 242 'opt': opt, |
| 243 'value': value, |
| 244 }) |
| 245 raise TypeError(msg) |
| 246 |
| 247 if opts.model: |
| 248 # If a model is defined, extract form fields from it. |
| 249 if opts.fields is None and opts.exclude is None: |
| 250 raise ImproperlyConfigured( |
| 251 "Creating a ModelForm without either the 'fields' attribute
" |
| 252 "or the 'exclude' attribute is prohibited; form %s " |
| 253 "needs updating." % name |
| 254 ) |
| 255 |
| 256 if opts.fields == ALL_FIELDS: |
| 257 # Sentinel for fields_for_model to indicate "get the list of |
| 258 # fields from the model" |
| 259 opts.fields = None |
| 260 |
| 261 fields = fields_for_model( |
| 262 opts.model, opts.fields, opts.exclude, opts.widgets, |
| 263 formfield_callback, opts.localized_fields, opts.labels, |
| 264 opts.help_texts, opts.error_messages, opts.field_classes, |
| 265 # limit_choices_to will be applied during ModelForm.__init__(). |
| 266 apply_limit_choices_to=False, |
| 267 ) |
| 268 |
| 269 # make sure opts.fields doesn't specify an invalid field |
| 270 none_model_fields = [k for k, v in six.iteritems(fields) if not v] |
| 271 missing_fields = (set(none_model_fields) - |
| 272 set(new_class.declared_fields.keys())) |
| 273 if missing_fields: |
| 274 message = 'Unknown field(s) (%s) specified for %s' |
| 275 message = message % (', '.join(missing_fields), |
| 276 opts.model.__name__) |
| 277 raise FieldError(message) |
| 278 # Override default model fields with any custom declared ones |
| 279 # (plus, include all the other declared fields). |
| 280 fields.update(new_class.declared_fields) |
| 281 else: |
| 282 fields = new_class.declared_fields |
| 283 |
| 284 new_class.base_fields = fields |
| 285 |
| 286 return new_class |
| 287 |
| 288 |
| 289 class BaseModelForm(BaseForm): |
| 290 def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, |
| 291 initial=None, error_class=ErrorList, label_suffix=None, |
| 292 empty_permitted=False, instance=None, use_required_attribute=No
ne): |
| 293 opts = self._meta |
| 294 if opts.model is None: |
| 295 raise ValueError('ModelForm has no model class specified.') |
| 296 if instance is None: |
| 297 # if we didn't get an instance, instantiate a new one |
| 298 self.instance = opts.model() |
| 299 object_data = {} |
| 300 else: |
| 301 self.instance = instance |
| 302 object_data = model_to_dict(instance, opts.fields, opts.exclude) |
| 303 # if initial was provided, it should override the values from instance |
| 304 if initial is not None: |
| 305 object_data.update(initial) |
| 306 # self._validate_unique will be set to True by BaseModelForm.clean(). |
| 307 # It is False by default so overriding self.clean() and failing to call |
| 308 # super will stop validate_unique from being called. |
| 309 self._validate_unique = False |
| 310 super(BaseModelForm, self).__init__( |
| 311 data, files, auto_id, prefix, object_data, error_class, |
| 312 label_suffix, empty_permitted, use_required_attribute=use_required_a
ttribute, |
| 313 ) |
| 314 for formfield in self.fields.values(): |
| 315 apply_limit_choices_to_to_formfield(formfield) |
| 316 |
| 317 def _get_validation_exclusions(self): |
| 318 """ |
| 319 For backwards-compatibility, several types of fields need to be |
| 320 excluded from model validation. See the following tickets for |
| 321 details: #12507, #12521, #12553 |
| 322 """ |
| 323 exclude = [] |
| 324 # Build up a list of fields that should be excluded from model field |
| 325 # validation and unique checks. |
| 326 for f in self.instance._meta.fields: |
| 327 field = f.name |
| 328 # Exclude fields that aren't on the form. The developer may be |
| 329 # adding these values to the model after form validation. |
| 330 if field not in self.fields: |
| 331 exclude.append(f.name) |
| 332 |
| 333 # Don't perform model validation on fields that were defined |
| 334 # manually on the form and excluded via the ModelForm's Meta |
| 335 # class. See #12901. |
| 336 elif self._meta.fields and field not in self._meta.fields: |
| 337 exclude.append(f.name) |
| 338 elif self._meta.exclude and field in self._meta.exclude: |
| 339 exclude.append(f.name) |
| 340 |
| 341 # Exclude fields that failed form validation. There's no need for |
| 342 # the model fields to validate them as well. |
| 343 elif field in self._errors.keys(): |
| 344 exclude.append(f.name) |
| 345 |
| 346 # Exclude empty fields that are not required by the form, if the |
| 347 # underlying model field is required. This keeps the model field |
| 348 # from raising a required error. Note: don't exclude the field from |
| 349 # validation if the model field allows blanks. If it does, the blank |
| 350 # value may be included in a unique check, so cannot be excluded |
| 351 # from validation. |
| 352 else: |
| 353 form_field = self.fields[field] |
| 354 field_value = self.cleaned_data.get(field) |
| 355 if not f.blank and not form_field.required and field_value in fo
rm_field.empty_values: |
| 356 exclude.append(f.name) |
| 357 return exclude |
| 358 |
| 359 def clean(self): |
| 360 self._validate_unique = True |
| 361 return self.cleaned_data |
| 362 |
| 363 def _update_errors(self, errors): |
| 364 # Override any validation error messages defined at the model level |
| 365 # with those defined at the form level. |
| 366 opts = self._meta |
| 367 |
| 368 # Allow the model generated by construct_instance() to raise |
| 369 # ValidationError and have them handled in the same way as others. |
| 370 if hasattr(errors, 'error_dict'): |
| 371 error_dict = errors.error_dict |
| 372 else: |
| 373 error_dict = {NON_FIELD_ERRORS: errors} |
| 374 |
| 375 for field, messages in error_dict.items(): |
| 376 if (field == NON_FIELD_ERRORS and opts.error_messages and |
| 377 NON_FIELD_ERRORS in opts.error_messages): |
| 378 error_messages = opts.error_messages[NON_FIELD_ERRORS] |
| 379 elif field in self.fields: |
| 380 error_messages = self.fields[field].error_messages |
| 381 else: |
| 382 continue |
| 383 |
| 384 for message in messages: |
| 385 if (isinstance(message, ValidationError) and |
| 386 message.code in error_messages): |
| 387 message.message = error_messages[message.code] |
| 388 |
| 389 self.add_error(None, errors) |
| 390 |
| 391 def _post_clean(self): |
| 392 opts = self._meta |
| 393 |
| 394 exclude = self._get_validation_exclusions() |
| 395 |
| 396 # Foreign Keys being used to represent inline relationships |
| 397 # are excluded from basic field value validation. This is for two |
| 398 # reasons: firstly, the value may not be supplied (#12507; the |
| 399 # case of providing new values to the admin); secondly the |
| 400 # object being referred to may not yet fully exist (#12749). |
| 401 # However, these fields *must* be included in uniqueness checks, |
| 402 # so this can't be part of _get_validation_exclusions(). |
| 403 for name, field in self.fields.items(): |
| 404 if isinstance(field, InlineForeignKeyField): |
| 405 exclude.append(name) |
| 406 |
| 407 try: |
| 408 self.instance = construct_instance(self, self.instance, opts.fields,
opts.exclude) |
| 409 except ValidationError as e: |
| 410 self._update_errors(e) |
| 411 |
| 412 try: |
| 413 self.instance.full_clean(exclude=exclude, validate_unique=False) |
| 414 except ValidationError as e: |
| 415 self._update_errors(e) |
| 416 |
| 417 # Validate uniqueness if needed. |
| 418 if self._validate_unique: |
| 419 self.validate_unique() |
| 420 |
| 421 def validate_unique(self): |
| 422 """ |
| 423 Calls the instance's validate_unique() method and updates the form's |
| 424 validation errors if any were raised. |
| 425 """ |
| 426 exclude = self._get_validation_exclusions() |
| 427 try: |
| 428 self.instance.validate_unique(exclude=exclude) |
| 429 except ValidationError as e: |
| 430 self._update_errors(e) |
| 431 |
| 432 def _save_m2m(self): |
| 433 """ |
| 434 Save the many-to-many fields and generic relations for this form. |
| 435 """ |
| 436 cleaned_data = self.cleaned_data |
| 437 exclude = self._meta.exclude |
| 438 fields = self._meta.fields |
| 439 opts = self.instance._meta |
| 440 # Note that for historical reasons we want to include also |
| 441 # private_fields here. (GenericRelation was previously a fake |
| 442 # m2m field). |
| 443 for f in chain(opts.many_to_many, opts.private_fields): |
| 444 if not hasattr(f, 'save_form_data'): |
| 445 continue |
| 446 if fields and f.name not in fields: |
| 447 continue |
| 448 if exclude and f.name in exclude: |
| 449 continue |
| 450 if f.name in cleaned_data: |
| 451 f.save_form_data(self.instance, cleaned_data[f.name]) |
| 452 |
| 453 def save(self, commit=True): |
| 454 """ |
| 455 Save this form's self.instance object if commit=True. Otherwise, add |
| 456 a save_m2m() method to the form which can be called after the instance |
| 457 is saved manually at a later time. Return the model instance. |
| 458 """ |
| 459 if self.errors: |
| 460 raise ValueError( |
| 461 "The %s could not be %s because the data didn't validate." % ( |
| 462 self.instance._meta.object_name, |
| 463 'created' if self.instance._state.adding else 'changed', |
| 464 ) |
| 465 ) |
| 466 if commit: |
| 467 # If committing, save the instance and the m2m data immediately. |
| 468 self.instance.save() |
| 469 self._save_m2m() |
| 470 else: |
| 471 # If not committing, add a method to the form to allow deferred |
| 472 # saving of m2m data. |
| 473 self.save_m2m = self._save_m2m |
| 474 return self.instance |
| 475 |
| 476 save.alters_data = True |
| 477 |
| 478 |
| 479 class ModelForm(six.with_metaclass(ModelFormMetaclass, BaseModelForm)): |
| 480 pass |
| 481 |
| 482 |
| 483 def modelform_factory(model, form=ModelForm, fields=None, exclude=None, |
| 484 formfield_callback=None, widgets=None, localized_fields=No
ne, |
| 485 labels=None, help_texts=None, error_messages=None, |
| 486 field_classes=None): |
| 487 """ |
| 488 Returns a ModelForm containing form fields for the given model. |
| 489 |
| 490 ``fields`` is an optional list of field names. If provided, only the named |
| 491 fields will be included in the returned fields. If omitted or '__all__', |
| 492 all fields will be used. |
| 493 |
| 494 ``exclude`` is an optional list of field names. If provided, the named |
| 495 fields will be excluded from the returned fields, even if they are listed |
| 496 in the ``fields`` argument. |
| 497 |
| 498 ``widgets`` is a dictionary of model field names mapped to a widget. |
| 499 |
| 500 ``localized_fields`` is a list of names of fields which should be localized. |
| 501 |
| 502 ``formfield_callback`` is a callable that takes a model field and returns |
| 503 a form field. |
| 504 |
| 505 ``labels`` is a dictionary of model field names mapped to a label. |
| 506 |
| 507 ``help_texts`` is a dictionary of model field names mapped to a help text. |
| 508 |
| 509 ``error_messages`` is a dictionary of model field names mapped to a |
| 510 dictionary of error messages. |
| 511 |
| 512 ``field_classes`` is a dictionary of model field names mapped to a form |
| 513 field class. |
| 514 """ |
| 515 # Create the inner Meta class. FIXME: ideally, we should be able to |
| 516 # construct a ModelForm without creating and passing in a temporary |
| 517 # inner class. |
| 518 |
| 519 # Build up a list of attributes that the Meta object will have. |
| 520 attrs = {'model': model} |
| 521 if fields is not None: |
| 522 attrs['fields'] = fields |
| 523 if exclude is not None: |
| 524 attrs['exclude'] = exclude |
| 525 if widgets is not None: |
| 526 attrs['widgets'] = widgets |
| 527 if localized_fields is not None: |
| 528 attrs['localized_fields'] = localized_fields |
| 529 if labels is not None: |
| 530 attrs['labels'] = labels |
| 531 if help_texts is not None: |
| 532 attrs['help_texts'] = help_texts |
| 533 if error_messages is not None: |
| 534 attrs['error_messages'] = error_messages |
| 535 if field_classes is not None: |
| 536 attrs['field_classes'] = field_classes |
| 537 |
| 538 # If parent form class already has an inner Meta, the Meta we're |
| 539 # creating needs to inherit from the parent's inner meta. |
| 540 parent = (object,) |
| 541 if hasattr(form, 'Meta'): |
| 542 parent = (form.Meta, object) |
| 543 Meta = type(str('Meta'), parent, attrs) |
| 544 if formfield_callback: |
| 545 Meta.formfield_callback = staticmethod(formfield_callback) |
| 546 # Give this new form class a reasonable name. |
| 547 class_name = model.__name__ + str('Form') |
| 548 |
| 549 # Class attributes for the new form class. |
| 550 form_class_attrs = { |
| 551 'Meta': Meta, |
| 552 'formfield_callback': formfield_callback |
| 553 } |
| 554 |
| 555 if (getattr(Meta, 'fields', None) is None and |
| 556 getattr(Meta, 'exclude', None) is None): |
| 557 raise ImproperlyConfigured( |
| 558 "Calling modelform_factory without defining 'fields' or " |
| 559 "'exclude' explicitly is prohibited." |
| 560 ) |
| 561 |
| 562 # Instantiate type(form) in order to use the same metaclass as form. |
| 563 return type(form)(class_name, (form,), form_class_attrs) |
| 564 |
| 565 |
| 566 # ModelFormSets ############################################################## |
| 567 |
| 568 class BaseModelFormSet(BaseFormSet): |
| 569 """ |
| 570 A ``FormSet`` for editing a queryset and/or adding new objects to it. |
| 571 """ |
| 572 model = None |
| 573 |
| 574 # Set of fields that must be unique among forms of this set. |
| 575 unique_fields = set() |
| 576 |
| 577 def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, |
| 578 queryset=None, **kwargs): |
| 579 self.queryset = queryset |
| 580 self.initial_extra = kwargs.pop('initial', None) |
| 581 defaults = {'data': data, 'files': files, 'auto_id': auto_id, 'prefix':
prefix} |
| 582 defaults.update(kwargs) |
| 583 super(BaseModelFormSet, self).__init__(**defaults) |
| 584 |
| 585 def initial_form_count(self): |
| 586 """Returns the number of forms that are required in this FormSet.""" |
| 587 if not (self.data or self.files): |
| 588 return len(self.get_queryset()) |
| 589 return super(BaseModelFormSet, self).initial_form_count() |
| 590 |
| 591 def _existing_object(self, pk): |
| 592 if not hasattr(self, '_object_dict'): |
| 593 self._object_dict = {o.pk: o for o in self.get_queryset()} |
| 594 return self._object_dict.get(pk) |
| 595 |
| 596 def _get_to_python(self, field): |
| 597 """ |
| 598 If the field is a related field, fetch the concrete field's (that |
| 599 is, the ultimate pointed-to field's) to_python. |
| 600 """ |
| 601 while field.remote_field is not None: |
| 602 field = field.remote_field.get_related_field() |
| 603 return field.to_python |
| 604 |
| 605 def _construct_form(self, i, **kwargs): |
| 606 if self.is_bound and i < self.initial_form_count(): |
| 607 pk_key = "%s-%s" % (self.add_prefix(i), self.model._meta.pk.name) |
| 608 pk = self.data[pk_key] |
| 609 pk_field = self.model._meta.pk |
| 610 to_python = self._get_to_python(pk_field) |
| 611 pk = to_python(pk) |
| 612 kwargs['instance'] = self._existing_object(pk) |
| 613 if i < self.initial_form_count() and 'instance' not in kwargs: |
| 614 kwargs['instance'] = self.get_queryset()[i] |
| 615 if i >= self.initial_form_count() and self.initial_extra: |
| 616 # Set initial values for extra forms |
| 617 try: |
| 618 kwargs['initial'] = self.initial_extra[i - self.initial_form_cou
nt()] |
| 619 except IndexError: |
| 620 pass |
| 621 return super(BaseModelFormSet, self)._construct_form(i, **kwargs) |
| 622 |
| 623 def get_queryset(self): |
| 624 if not hasattr(self, '_queryset'): |
| 625 if self.queryset is not None: |
| 626 qs = self.queryset |
| 627 else: |
| 628 qs = self.model._default_manager.get_queryset() |
| 629 |
| 630 # If the queryset isn't already ordered we need to add an |
| 631 # artificial ordering here to make sure that all formsets |
| 632 # constructed from this queryset have the same form order. |
| 633 if not qs.ordered: |
| 634 qs = qs.order_by(self.model._meta.pk.name) |
| 635 |
| 636 # Removed queryset limiting here. As per discussion re: #13023 |
| 637 # on django-dev, max_num should not prevent existing |
| 638 # related objects/inlines from being displayed. |
| 639 self._queryset = qs |
| 640 return self._queryset |
| 641 |
| 642 def save_new(self, form, commit=True): |
| 643 """Saves and returns a new model instance for the given form.""" |
| 644 return form.save(commit=commit) |
| 645 |
| 646 def save_existing(self, form, instance, commit=True): |
| 647 """Saves and returns an existing model instance for the given form.""" |
| 648 return form.save(commit=commit) |
| 649 |
| 650 def delete_existing(self, obj, commit=True): |
| 651 """Deletes an existing model instance.""" |
| 652 if commit: |
| 653 obj.delete() |
| 654 |
| 655 def save(self, commit=True): |
| 656 """Saves model instances for every form, adding and changing instances |
| 657 as necessary, and returns the list of instances. |
| 658 """ |
| 659 if not commit: |
| 660 self.saved_forms = [] |
| 661 |
| 662 def save_m2m(): |
| 663 for form in self.saved_forms: |
| 664 form.save_m2m() |
| 665 self.save_m2m = save_m2m |
| 666 return self.save_existing_objects(commit) + self.save_new_objects(commit
) |
| 667 |
| 668 save.alters_data = True |
| 669 |
| 670 def clean(self): |
| 671 self.validate_unique() |
| 672 |
| 673 def validate_unique(self): |
| 674 # Collect unique_checks and date_checks to run from all the forms. |
| 675 all_unique_checks = set() |
| 676 all_date_checks = set() |
| 677 forms_to_delete = self.deleted_forms |
| 678 valid_forms = [form for form in self.forms if form.is_valid() and form n
ot in forms_to_delete] |
| 679 for form in valid_forms: |
| 680 exclude = form._get_validation_exclusions() |
| 681 unique_checks, date_checks = form.instance._get_unique_checks(exclud
e=exclude) |
| 682 all_unique_checks = all_unique_checks.union(set(unique_checks)) |
| 683 all_date_checks = all_date_checks.union(set(date_checks)) |
| 684 |
| 685 errors = [] |
| 686 # Do each of the unique checks (unique and unique_together) |
| 687 for uclass, unique_check in all_unique_checks: |
| 688 seen_data = set() |
| 689 for form in valid_forms: |
| 690 # Get the data for the set of fields that must be unique among t
he forms. |
| 691 row_data = ( |
| 692 field if field in self.unique_fields else form.cleaned_data[
field] |
| 693 for field in unique_check if field in form.cleaned_data |
| 694 ) |
| 695 # Reduce Model instances to their primary key values |
| 696 row_data = tuple(d._get_pk_val() if hasattr(d, '_get_pk_val') el
se d |
| 697 for d in row_data) |
| 698 if row_data and None not in row_data: |
| 699 # if we've already seen it then we have a uniqueness failure |
| 700 if row_data in seen_data: |
| 701 # poke error messages into the right places and mark |
| 702 # the form as invalid |
| 703 errors.append(self.get_unique_error_message(unique_check
)) |
| 704 form._errors[NON_FIELD_ERRORS] = self.error_class([self.
get_form_error()]) |
| 705 # remove the data from the cleaned_data dict since it wa
s invalid |
| 706 for field in unique_check: |
| 707 if field in form.cleaned_data: |
| 708 del form.cleaned_data[field] |
| 709 # mark the data as seen |
| 710 seen_data.add(row_data) |
| 711 # iterate over each of the date checks now |
| 712 for date_check in all_date_checks: |
| 713 seen_data = set() |
| 714 uclass, lookup, field, unique_for = date_check |
| 715 for form in valid_forms: |
| 716 # see if we have data for both fields |
| 717 if (form.cleaned_data and form.cleaned_data[field] is not None a
nd |
| 718 form.cleaned_data[unique_for] is not None): |
| 719 # if it's a date lookup we need to get the data for all the
fields |
| 720 if lookup == 'date': |
| 721 date = form.cleaned_data[unique_for] |
| 722 date_data = (date.year, date.month, date.day) |
| 723 # otherwise it's just the attribute on the date/datetime |
| 724 # object |
| 725 else: |
| 726 date_data = (getattr(form.cleaned_data[unique_for], look
up),) |
| 727 data = (form.cleaned_data[field],) + date_data |
| 728 # if we've already seen it then we have a uniqueness failure |
| 729 if data in seen_data: |
| 730 # poke error messages into the right places and mark |
| 731 # the form as invalid |
| 732 errors.append(self.get_date_error_message(date_check)) |
| 733 form._errors[NON_FIELD_ERRORS] = self.error_class([self.
get_form_error()]) |
| 734 # remove the data from the cleaned_data dict since it wa
s invalid |
| 735 del form.cleaned_data[field] |
| 736 # mark the data as seen |
| 737 seen_data.add(data) |
| 738 |
| 739 if errors: |
| 740 raise ValidationError(errors) |
| 741 |
| 742 def get_unique_error_message(self, unique_check): |
| 743 if len(unique_check) == 1: |
| 744 return ugettext("Please correct the duplicate data for %(field)s.")
% { |
| 745 "field": unique_check[0], |
| 746 } |
| 747 else: |
| 748 return ugettext("Please correct the duplicate data for %(field)s, wh
ich must be unique.") % { |
| 749 "field": get_text_list(unique_check, six.text_type(_("and"))), |
| 750 } |
| 751 |
| 752 def get_date_error_message(self, date_check): |
| 753 return ugettext( |
| 754 "Please correct the duplicate data for %(field_name)s " |
| 755 "which must be unique for the %(lookup)s in %(date_field)s." |
| 756 ) % { |
| 757 'field_name': date_check[2], |
| 758 'date_field': date_check[3], |
| 759 'lookup': six.text_type(date_check[1]), |
| 760 } |
| 761 |
| 762 def get_form_error(self): |
| 763 return ugettext("Please correct the duplicate values below.") |
| 764 |
| 765 def save_existing_objects(self, commit=True): |
| 766 self.changed_objects = [] |
| 767 self.deleted_objects = [] |
| 768 if not self.initial_forms: |
| 769 return [] |
| 770 |
| 771 saved_instances = [] |
| 772 forms_to_delete = self.deleted_forms |
| 773 for form in self.initial_forms: |
| 774 obj = form.instance |
| 775 # If the pk is None, it means either: |
| 776 # 1. The object is an unexpected empty model, created by invalid |
| 777 # POST data such as an object outside the formset's queryset. |
| 778 # 2. The object was already deleted from the database. |
| 779 if obj.pk is None: |
| 780 continue |
| 781 if form in forms_to_delete: |
| 782 self.deleted_objects.append(obj) |
| 783 self.delete_existing(obj, commit=commit) |
| 784 elif form.has_changed(): |
| 785 self.changed_objects.append((obj, form.changed_data)) |
| 786 saved_instances.append(self.save_existing(form, obj, commit=comm
it)) |
| 787 if not commit: |
| 788 self.saved_forms.append(form) |
| 789 return saved_instances |
| 790 |
| 791 def save_new_objects(self, commit=True): |
| 792 self.new_objects = [] |
| 793 for form in self.extra_forms: |
| 794 if not form.has_changed(): |
| 795 continue |
| 796 # If someone has marked an add form for deletion, don't save the |
| 797 # object. |
| 798 if self.can_delete and self._should_delete_form(form): |
| 799 continue |
| 800 self.new_objects.append(self.save_new(form, commit=commit)) |
| 801 if not commit: |
| 802 self.saved_forms.append(form) |
| 803 return self.new_objects |
| 804 |
| 805 def add_fields(self, form, index): |
| 806 """Add a hidden field for the object's primary key.""" |
| 807 from django.db.models import AutoField, OneToOneField, ForeignKey |
| 808 self._pk_field = pk = self.model._meta.pk |
| 809 # If a pk isn't editable, then it won't be on the form, so we need to |
| 810 # add it here so we can tell which object is which when we get the |
| 811 # data back. Generally, pk.editable should be false, but for some |
| 812 # reason, auto_created pk fields and AutoField's editable attribute is |
| 813 # True, so check for that as well. |
| 814 |
| 815 def pk_is_not_editable(pk): |
| 816 return ( |
| 817 (not pk.editable) or (pk.auto_created or isinstance(pk, AutoFiel
d)) or ( |
| 818 pk.remote_field and pk.remote_field.parent_link and |
| 819 pk_is_not_editable(pk.remote_field.model._meta.pk) |
| 820 ) |
| 821 ) |
| 822 if pk_is_not_editable(pk) or pk.name not in form.fields: |
| 823 if form.is_bound: |
| 824 # If we're adding the related instance, ignore its primary key |
| 825 # as it could be an auto-generated default which isn't actually |
| 826 # in the database. |
| 827 pk_value = None if form.instance._state.adding else form.instanc
e.pk |
| 828 else: |
| 829 try: |
| 830 if index is not None: |
| 831 pk_value = self.get_queryset()[index].pk |
| 832 else: |
| 833 pk_value = None |
| 834 except IndexError: |
| 835 pk_value = None |
| 836 if isinstance(pk, OneToOneField) or isinstance(pk, ForeignKey): |
| 837 qs = pk.remote_field.model._default_manager.get_queryset() |
| 838 else: |
| 839 qs = self.model._default_manager.get_queryset() |
| 840 qs = qs.using(form.instance._state.db) |
| 841 if form._meta.widgets: |
| 842 widget = form._meta.widgets.get(self._pk_field.name, HiddenInput
) |
| 843 else: |
| 844 widget = HiddenInput |
| 845 form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_v
alue, required=False, widget=widget) |
| 846 super(BaseModelFormSet, self).add_fields(form, index) |
| 847 |
| 848 |
| 849 def modelformset_factory(model, form=ModelForm, formfield_callback=None, |
| 850 formset=BaseModelFormSet, extra=1, can_delete=False, |
| 851 can_order=False, max_num=None, fields=None, exclude=Non
e, |
| 852 widgets=None, validate_max=False, localized_fields=None
, |
| 853 labels=None, help_texts=None, error_messages=None, |
| 854 min_num=None, validate_min=False, field_classes=None): |
| 855 """ |
| 856 Returns a FormSet class for the given Django model class. |
| 857 """ |
| 858 meta = getattr(form, 'Meta', None) |
| 859 if (getattr(meta, 'fields', fields) is None and |
| 860 getattr(meta, 'exclude', exclude) is None): |
| 861 raise ImproperlyConfigured( |
| 862 "Calling modelformset_factory without defining 'fields' or " |
| 863 "'exclude' explicitly is prohibited." |
| 864 ) |
| 865 |
| 866 form = modelform_factory(model, form=form, fields=fields, exclude=exclude, |
| 867 formfield_callback=formfield_callback, |
| 868 widgets=widgets, localized_fields=localized_fields, |
| 869 labels=labels, help_texts=help_texts, |
| 870 error_messages=error_messages, field_classes=field_
classes) |
| 871 FormSet = formset_factory(form, formset, extra=extra, min_num=min_num, max_n
um=max_num, |
| 872 can_order=can_order, can_delete=can_delete, |
| 873 validate_min=validate_min, validate_max=validate_m
ax) |
| 874 FormSet.model = model |
| 875 return FormSet |
| 876 |
| 877 |
| 878 # InlineFormSets ############################################################# |
| 879 |
| 880 class BaseInlineFormSet(BaseModelFormSet): |
| 881 """A formset for child objects related to a parent.""" |
| 882 def __init__(self, data=None, files=None, instance=None, |
| 883 save_as_new=False, prefix=None, queryset=None, **kwargs): |
| 884 if instance is None: |
| 885 self.instance = self.fk.remote_field.model() |
| 886 else: |
| 887 self.instance = instance |
| 888 self.save_as_new = save_as_new |
| 889 if queryset is None: |
| 890 queryset = self.model._default_manager |
| 891 if self.instance.pk is not None: |
| 892 qs = queryset.filter(**{self.fk.name: self.instance}) |
| 893 else: |
| 894 qs = queryset.none() |
| 895 self.unique_fields = {self.fk.name} |
| 896 super(BaseInlineFormSet, self).__init__(data, files, prefix=prefix, |
| 897 queryset=qs, **kwargs) |
| 898 |
| 899 # Add the generated field to form._meta.fields if it's defined to make |
| 900 # sure validation isn't skipped on that field. |
| 901 if self.form._meta.fields and self.fk.name not in self.form._meta.fields
: |
| 902 if isinstance(self.form._meta.fields, tuple): |
| 903 self.form._meta.fields = list(self.form._meta.fields) |
| 904 self.form._meta.fields.append(self.fk.name) |
| 905 |
| 906 def initial_form_count(self): |
| 907 if self.save_as_new: |
| 908 return 0 |
| 909 return super(BaseInlineFormSet, self).initial_form_count() |
| 910 |
| 911 def _construct_form(self, i, **kwargs): |
| 912 form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs) |
| 913 if self.save_as_new: |
| 914 mutable = getattr(form.data, '_mutable', None) |
| 915 # Allow modifying an immutable QueryDict. |
| 916 if mutable is not None: |
| 917 form.data._mutable = True |
| 918 # Remove the primary key from the form's data, we are only |
| 919 # creating new instances |
| 920 form.data[form.add_prefix(self._pk_field.name)] = None |
| 921 # Remove the foreign key from the form's data |
| 922 form.data[form.add_prefix(self.fk.name)] = None |
| 923 if mutable is not None: |
| 924 form.data._mutable = mutable |
| 925 |
| 926 # Set the fk value here so that the form can do its validation. |
| 927 fk_value = self.instance.pk |
| 928 if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.p
k.name: |
| 929 fk_value = getattr(self.instance, self.fk.remote_field.field_name) |
| 930 fk_value = getattr(fk_value, 'pk', fk_value) |
| 931 setattr(form.instance, self.fk.get_attname(), fk_value) |
| 932 return form |
| 933 |
| 934 @classmethod |
| 935 def get_default_prefix(cls): |
| 936 return cls.fk.remote_field.get_accessor_name(model=cls.model).replace('+
', '') |
| 937 |
| 938 def save_new(self, form, commit=True): |
| 939 # Ensure the latest copy of the related instance is present on each |
| 940 # form (it may have been saved after the formset was originally |
| 941 # instantiated). |
| 942 setattr(form.instance, self.fk.name, self.instance) |
| 943 # Use commit=False so we can assign the parent key afterwards, then |
| 944 # save the object. |
| 945 obj = form.save(commit=False) |
| 946 pk_value = getattr(self.instance, self.fk.remote_field.field_name) |
| 947 setattr(obj, self.fk.get_attname(), getattr(pk_value, 'pk', pk_value)) |
| 948 if commit: |
| 949 obj.save() |
| 950 # form.save_m2m() can be called via the formset later on if commit=False |
| 951 if commit and hasattr(form, 'save_m2m'): |
| 952 form.save_m2m() |
| 953 return obj |
| 954 |
| 955 def add_fields(self, form, index): |
| 956 super(BaseInlineFormSet, self).add_fields(form, index) |
| 957 if self._pk_field == self.fk: |
| 958 name = self._pk_field.name |
| 959 kwargs = {'pk_field': True} |
| 960 else: |
| 961 # The foreign key field might not be on the form, so we poke at the |
| 962 # Model field to get the label, since we need that for error message
s. |
| 963 name = self.fk.name |
| 964 kwargs = { |
| 965 'label': getattr(form.fields.get(name), 'label', capfirst(self.f
k.verbose_name)) |
| 966 } |
| 967 if self.fk.remote_field.field_name != self.fk.remote_field.model._me
ta.pk.name: |
| 968 kwargs['to_field'] = self.fk.remote_field.field_name |
| 969 |
| 970 # If we're adding a new object, ignore a parent's auto-generated key |
| 971 # as it will be regenerated on the save request. |
| 972 if self.instance._state.adding: |
| 973 if kwargs.get('to_field') is not None: |
| 974 to_field = self.instance._meta.get_field(kwargs['to_field']) |
| 975 else: |
| 976 to_field = self.instance._meta.pk |
| 977 if to_field.has_default(): |
| 978 setattr(self.instance, to_field.attname, None) |
| 979 |
| 980 form.fields[name] = InlineForeignKeyField(self.instance, **kwargs) |
| 981 |
| 982 def get_unique_error_message(self, unique_check): |
| 983 unique_check = [field for field in unique_check if field != self.fk.name
] |
| 984 return super(BaseInlineFormSet, self).get_unique_error_message(unique_ch
eck) |
| 985 |
| 986 |
| 987 def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False): |
| 988 """ |
| 989 Finds and returns the ForeignKey from model to parent if there is one |
| 990 (returns None if can_fail is True and no such field exists). If fk_name is |
| 991 provided, assume it is the name of the ForeignKey field. Unless can_fail is |
| 992 True, an exception is raised if there is no ForeignKey from model to |
| 993 parent_model. |
| 994 """ |
| 995 # avoid circular import |
| 996 from django.db.models import ForeignKey |
| 997 opts = model._meta |
| 998 if fk_name: |
| 999 fks_to_parent = [f for f in opts.fields if f.name == fk_name] |
| 1000 if len(fks_to_parent) == 1: |
| 1001 fk = fks_to_parent[0] |
| 1002 if not isinstance(fk, ForeignKey) or \ |
| 1003 (fk.remote_field.model != parent_model and |
| 1004 fk.remote_field.model not in parent_model._meta.get_parent_
list()): |
| 1005 raise ValueError( |
| 1006 "fk_name '%s' is not a ForeignKey to '%s'." % (fk_name, pare
nt_model._meta.label) |
| 1007 ) |
| 1008 elif len(fks_to_parent) == 0: |
| 1009 raise ValueError( |
| 1010 "'%s' has no field named '%s'." % (model._meta.label, fk_name) |
| 1011 ) |
| 1012 else: |
| 1013 # Try to discover what the ForeignKey from model to parent_model is |
| 1014 fks_to_parent = [ |
| 1015 f for f in opts.fields |
| 1016 if isinstance(f, ForeignKey) and ( |
| 1017 f.remote_field.model == parent_model or |
| 1018 f.remote_field.model in parent_model._meta.get_parent_list() |
| 1019 ) |
| 1020 ] |
| 1021 if len(fks_to_parent) == 1: |
| 1022 fk = fks_to_parent[0] |
| 1023 elif len(fks_to_parent) == 0: |
| 1024 if can_fail: |
| 1025 return |
| 1026 raise ValueError( |
| 1027 "'%s' has no ForeignKey to '%s'." % ( |
| 1028 model._meta.label, |
| 1029 parent_model._meta.label, |
| 1030 ) |
| 1031 ) |
| 1032 else: |
| 1033 raise ValueError( |
| 1034 "'%s' has more than one ForeignKey to '%s'." % ( |
| 1035 model._meta.label, |
| 1036 parent_model._meta.label, |
| 1037 ) |
| 1038 ) |
| 1039 return fk |
| 1040 |
| 1041 |
| 1042 def inlineformset_factory(parent_model, model, form=ModelForm, |
| 1043 formset=BaseInlineFormSet, fk_name=None, |
| 1044 fields=None, exclude=None, extra=3, can_order=False, |
| 1045 can_delete=True, max_num=None, formfield_callback=None
, |
| 1046 widgets=None, validate_max=False, localized_fields=Non
e, |
| 1047 labels=None, help_texts=None, error_messages=None, |
| 1048 min_num=None, validate_min=False, field_classes=None): |
| 1049 """ |
| 1050 Returns an ``InlineFormSet`` for the given kwargs. |
| 1051 |
| 1052 You must provide ``fk_name`` if ``model`` has more than one ``ForeignKey`` |
| 1053 to ``parent_model``. |
| 1054 """ |
| 1055 fk = _get_foreign_key(parent_model, model, fk_name=fk_name) |
| 1056 # enforce a max_num=1 when the foreign key to the parent model is unique. |
| 1057 if fk.unique: |
| 1058 max_num = 1 |
| 1059 kwargs = { |
| 1060 'form': form, |
| 1061 'formfield_callback': formfield_callback, |
| 1062 'formset': formset, |
| 1063 'extra': extra, |
| 1064 'can_delete': can_delete, |
| 1065 'can_order': can_order, |
| 1066 'fields': fields, |
| 1067 'exclude': exclude, |
| 1068 'min_num': min_num, |
| 1069 'max_num': max_num, |
| 1070 'widgets': widgets, |
| 1071 'validate_min': validate_min, |
| 1072 'validate_max': validate_max, |
| 1073 'localized_fields': localized_fields, |
| 1074 'labels': labels, |
| 1075 'help_texts': help_texts, |
| 1076 'error_messages': error_messages, |
| 1077 'field_classes': field_classes, |
| 1078 } |
| 1079 FormSet = modelformset_factory(model, **kwargs) |
| 1080 FormSet.fk = fk |
| 1081 return FormSet |
| 1082 |
| 1083 |
| 1084 # Fields ##################################################################### |
| 1085 |
| 1086 class InlineForeignKeyField(Field): |
| 1087 """ |
| 1088 A basic integer field that deals with validating the given value to a |
| 1089 given parent instance in an inline. |
| 1090 """ |
| 1091 widget = HiddenInput |
| 1092 default_error_messages = { |
| 1093 'invalid_choice': _('The inline foreign key did not match the parent ins
tance primary key.'), |
| 1094 } |
| 1095 |
| 1096 def __init__(self, parent_instance, *args, **kwargs): |
| 1097 self.parent_instance = parent_instance |
| 1098 self.pk_field = kwargs.pop("pk_field", False) |
| 1099 self.to_field = kwargs.pop("to_field", None) |
| 1100 if self.parent_instance is not None: |
| 1101 if self.to_field: |
| 1102 kwargs["initial"] = getattr(self.parent_instance, self.to_field) |
| 1103 else: |
| 1104 kwargs["initial"] = self.parent_instance.pk |
| 1105 kwargs["required"] = False |
| 1106 super(InlineForeignKeyField, self).__init__(*args, **kwargs) |
| 1107 |
| 1108 def clean(self, value): |
| 1109 if value in self.empty_values: |
| 1110 if self.pk_field: |
| 1111 return None |
| 1112 # if there is no value act as we did before. |
| 1113 return self.parent_instance |
| 1114 # ensure the we compare the values as equal types. |
| 1115 if self.to_field: |
| 1116 orig = getattr(self.parent_instance, self.to_field) |
| 1117 else: |
| 1118 orig = self.parent_instance.pk |
| 1119 if force_text(value) != force_text(orig): |
| 1120 raise ValidationError(self.error_messages['invalid_choice'], code='i
nvalid_choice') |
| 1121 return self.parent_instance |
| 1122 |
| 1123 def has_changed(self, initial, data): |
| 1124 return False |
| 1125 |
| 1126 |
| 1127 class ModelChoiceIterator(object): |
| 1128 def __init__(self, field): |
| 1129 self.field = field |
| 1130 self.queryset = field.queryset |
| 1131 |
| 1132 def __iter__(self): |
| 1133 if self.field.empty_label is not None: |
| 1134 yield ("", self.field.empty_label) |
| 1135 queryset = self.queryset.all() |
| 1136 # Can't use iterator() when queryset uses prefetch_related() |
| 1137 if not queryset._prefetch_related_lookups: |
| 1138 queryset = queryset.iterator() |
| 1139 for obj in queryset: |
| 1140 yield self.choice(obj) |
| 1141 |
| 1142 def __len__(self): |
| 1143 return (len(self.queryset) + (1 if self.field.empty_label is not None el
se 0)) |
| 1144 |
| 1145 def choice(self, obj): |
| 1146 return (self.field.prepare_value(obj), self.field.label_from_instance(ob
j)) |
| 1147 |
| 1148 |
| 1149 class ModelChoiceField(ChoiceField): |
| 1150 """A ChoiceField whose choices are a model QuerySet.""" |
| 1151 # This class is a subclass of ChoiceField for purity, but it doesn't |
| 1152 # actually use any of ChoiceField's implementation. |
| 1153 default_error_messages = { |
| 1154 'invalid_choice': _('Select a valid choice. That choice is not one of' |
| 1155 ' the available choices.'), |
| 1156 } |
| 1157 iterator = ModelChoiceIterator |
| 1158 |
| 1159 def __init__(self, queryset, empty_label="---------", |
| 1160 required=True, widget=None, label=None, initial=None, |
| 1161 help_text='', to_field_name=None, limit_choices_to=None, |
| 1162 *args, **kwargs): |
| 1163 if required and (initial is not None): |
| 1164 self.empty_label = None |
| 1165 else: |
| 1166 self.empty_label = empty_label |
| 1167 |
| 1168 # Call Field instead of ChoiceField __init__() because we don't need |
| 1169 # ChoiceField.__init__(). |
| 1170 Field.__init__(self, required, widget, label, initial, help_text, |
| 1171 *args, **kwargs) |
| 1172 self.queryset = queryset |
| 1173 self.limit_choices_to = limit_choices_to # limit the queryset later. |
| 1174 self.to_field_name = to_field_name |
| 1175 |
| 1176 def get_limit_choices_to(self): |
| 1177 """ |
| 1178 Returns ``limit_choices_to`` for this form field. |
| 1179 |
| 1180 If it is a callable, it will be invoked and the result will be |
| 1181 returned. |
| 1182 """ |
| 1183 if callable(self.limit_choices_to): |
| 1184 return self.limit_choices_to() |
| 1185 return self.limit_choices_to |
| 1186 |
| 1187 def __deepcopy__(self, memo): |
| 1188 result = super(ChoiceField, self).__deepcopy__(memo) |
| 1189 # Need to force a new ModelChoiceIterator to be created, bug #11183 |
| 1190 if self.queryset is not None: |
| 1191 result.queryset = self.queryset.all() |
| 1192 return result |
| 1193 |
| 1194 def _get_queryset(self): |
| 1195 return self._queryset |
| 1196 |
| 1197 def _set_queryset(self, queryset): |
| 1198 self._queryset = queryset |
| 1199 self.widget.choices = self.choices |
| 1200 |
| 1201 queryset = property(_get_queryset, _set_queryset) |
| 1202 |
| 1203 # this method will be used to create object labels by the QuerySetIterator. |
| 1204 # Override it to customize the label. |
| 1205 def label_from_instance(self, obj): |
| 1206 """ |
| 1207 This method is used to convert objects into strings; it's used to |
| 1208 generate the labels for the choices presented by this object. Subclasses |
| 1209 can override this method to customize the display of the choices. |
| 1210 """ |
| 1211 return force_text(obj) |
| 1212 |
| 1213 def _get_choices(self): |
| 1214 # If self._choices is set, then somebody must have manually set |
| 1215 # the property self.choices. In this case, just return self._choices. |
| 1216 if hasattr(self, '_choices'): |
| 1217 return self._choices |
| 1218 |
| 1219 # Otherwise, execute the QuerySet in self.queryset to determine the |
| 1220 # choices dynamically. Return a fresh ModelChoiceIterator that has not b
een |
| 1221 # consumed. Note that we're instantiating a new ModelChoiceIterator *eac
h* |
| 1222 # time _get_choices() is called (and, thus, each time self.choices is |
| 1223 # accessed) so that we can ensure the QuerySet has not been consumed. Th
is |
| 1224 # construct might look complicated but it allows for lazy evaluation of |
| 1225 # the queryset. |
| 1226 return self.iterator(self) |
| 1227 |
| 1228 choices = property(_get_choices, ChoiceField._set_choices) |
| 1229 |
| 1230 def prepare_value(self, value): |
| 1231 if hasattr(value, '_meta'): |
| 1232 if self.to_field_name: |
| 1233 return value.serializable_value(self.to_field_name) |
| 1234 else: |
| 1235 return value.pk |
| 1236 return super(ModelChoiceField, self).prepare_value(value) |
| 1237 |
| 1238 def to_python(self, value): |
| 1239 if value in self.empty_values: |
| 1240 return None |
| 1241 try: |
| 1242 key = self.to_field_name or 'pk' |
| 1243 value = self.queryset.get(**{key: value}) |
| 1244 except (ValueError, TypeError, self.queryset.model.DoesNotExist): |
| 1245 raise ValidationError(self.error_messages['invalid_choice'], code='i
nvalid_choice') |
| 1246 return value |
| 1247 |
| 1248 def validate(self, value): |
| 1249 return Field.validate(self, value) |
| 1250 |
| 1251 def has_changed(self, initial, data): |
| 1252 if self.disabled: |
| 1253 return False |
| 1254 initial_value = initial if initial is not None else '' |
| 1255 data_value = data if data is not None else '' |
| 1256 return force_text(self.prepare_value(initial_value)) != force_text(data_
value) |
| 1257 |
| 1258 |
| 1259 class ModelMultipleChoiceField(ModelChoiceField): |
| 1260 """A MultipleChoiceField whose choices are a model QuerySet.""" |
| 1261 widget = SelectMultiple |
| 1262 hidden_widget = MultipleHiddenInput |
| 1263 default_error_messages = { |
| 1264 'list': _('Enter a list of values.'), |
| 1265 'invalid_choice': _('Select a valid choice. %(value)s is not one of the' |
| 1266 ' available choices.'), |
| 1267 'invalid_pk_value': _('"%(pk)s" is not a valid value for a primary key.'
) |
| 1268 } |
| 1269 |
| 1270 def __init__(self, queryset, required=True, widget=None, label=None, |
| 1271 initial=None, help_text='', *args, **kwargs): |
| 1272 super(ModelMultipleChoiceField, self).__init__( |
| 1273 queryset, None, required, widget, label, initial, help_text, |
| 1274 *args, **kwargs |
| 1275 ) |
| 1276 |
| 1277 def to_python(self, value): |
| 1278 if not value: |
| 1279 return [] |
| 1280 return list(self._check_values(value)) |
| 1281 |
| 1282 def clean(self, value): |
| 1283 value = self.prepare_value(value) |
| 1284 if self.required and not value: |
| 1285 raise ValidationError(self.error_messages['required'], code='require
d') |
| 1286 elif not self.required and not value: |
| 1287 return self.queryset.none() |
| 1288 if not isinstance(value, (list, tuple)): |
| 1289 raise ValidationError(self.error_messages['list'], code='list') |
| 1290 qs = self._check_values(value) |
| 1291 # Since this overrides the inherited ModelChoiceField.clean |
| 1292 # we run custom validators here |
| 1293 self.run_validators(value) |
| 1294 return qs |
| 1295 |
| 1296 def _check_values(self, value): |
| 1297 """ |
| 1298 Given a list of possible PK values, returns a QuerySet of the |
| 1299 corresponding objects. Raises a ValidationError if a given value is |
| 1300 invalid (not a valid PK, not in the queryset, etc.) |
| 1301 """ |
| 1302 key = self.to_field_name or 'pk' |
| 1303 # deduplicate given values to avoid creating many querysets or |
| 1304 # requiring the database backend deduplicate efficiently. |
| 1305 try: |
| 1306 value = frozenset(value) |
| 1307 except TypeError: |
| 1308 # list of lists isn't hashable, for example |
| 1309 raise ValidationError( |
| 1310 self.error_messages['list'], |
| 1311 code='list', |
| 1312 ) |
| 1313 for pk in value: |
| 1314 try: |
| 1315 self.queryset.filter(**{key: pk}) |
| 1316 except (ValueError, TypeError): |
| 1317 raise ValidationError( |
| 1318 self.error_messages['invalid_pk_value'], |
| 1319 code='invalid_pk_value', |
| 1320 params={'pk': pk}, |
| 1321 ) |
| 1322 qs = self.queryset.filter(**{'%s__in' % key: value}) |
| 1323 pks = set(force_text(getattr(o, key)) for o in qs) |
| 1324 for val in value: |
| 1325 if force_text(val) not in pks: |
| 1326 raise ValidationError( |
| 1327 self.error_messages['invalid_choice'], |
| 1328 code='invalid_choice', |
| 1329 params={'value': val}, |
| 1330 ) |
| 1331 return qs |
| 1332 |
| 1333 def prepare_value(self, value): |
| 1334 if (hasattr(value, '__iter__') and |
| 1335 not isinstance(value, six.text_type) and |
| 1336 not hasattr(value, '_meta')): |
| 1337 return [super(ModelMultipleChoiceField, self).prepare_value(v) for v
in value] |
| 1338 return super(ModelMultipleChoiceField, self).prepare_value(value) |
| 1339 |
| 1340 def has_changed(self, initial, data): |
| 1341 if self.disabled: |
| 1342 return False |
| 1343 if initial is None: |
| 1344 initial = [] |
| 1345 if data is None: |
| 1346 data = [] |
| 1347 if len(initial) != len(data): |
| 1348 return True |
| 1349 initial_set = set(force_text(value) for value in self.prepare_value(init
ial)) |
| 1350 data_set = set(force_text(value) for value in data) |
| 1351 return data_set != initial_set |
| 1352 |
| 1353 |
| 1354 def modelform_defines_fields(form_class): |
| 1355 return (form_class is not None and ( |
| 1356 hasattr(form_class, '_meta') and |
| 1357 (form_class._meta.fields is not None or |
| 1358 form_class._meta.exclude is not None) |
| 1359 )) |
OLD | NEW |