Django

Code

root/django/branches/newforms-admin/django/newforms/models.py

Revision 7930, 24.3 kB (checked in by brosner, 4 months ago)

newforms-admin: Fixed #7230 -- Added a save_m2m method to BaseModelFormSet? when commit=False is passed to save. Thanks Books Travis for the original report.

  • Property svn:eol-style set to native
Line 
1 """
2 Helper functions for creating Form classes from Django models
3 and database field objects.
4 """
5
6 from warnings import warn
7
8 from django.utils.translation import ugettext_lazy as _
9 from django.utils.encoding import smart_unicode
10 from django.utils.datastructures import SortedDict
11 from django.core.exceptions import ImproperlyConfigured
12
13 from util import ValidationError, ErrorList
14 from forms import BaseForm, get_declared_fields
15 from fields import Field, ChoiceField, IntegerField, EMPTY_VALUES
16 from widgets import Select, SelectMultiple, HiddenInput, MultipleHiddenInput
17 from widgets import media_property
18 from formsets import BaseFormSet, formset_factory, DELETION_FIELD_NAME
19
20 __all__ = (
21     'ModelForm', 'BaseModelForm', 'model_to_dict', 'fields_for_model',
22     'save_instance', 'form_for_model', 'form_for_instance', 'form_for_fields',
23     'ModelChoiceField', 'ModelMultipleChoiceField',
24 )
25
26 def save_instance(form, instance, fields=None, fail_message='saved',
27                   commit=True):
28     """
29     Saves bound Form ``form``'s cleaned_data into model instance ``instance``.
30
31     If commit=True, then the changes to ``instance`` will be saved to the
32     database. Returns ``instance``.
33     """
34     from django.db import models
35     opts = instance._meta
36     if form.errors:
37         raise ValueError("The %s could not be %s because the data didn't"
38                          " validate." % (opts.object_name, fail_message))
39     cleaned_data = form.cleaned_data
40     for f in opts.fields:
41         if not f.editable or isinstance(f, models.AutoField) \
42                 or not f.name in cleaned_data:
43             continue
44         if fields and f.name not in fields:
45             continue
46         f.save_form_data(instance, cleaned_data[f.name])
47     # Wrap up the saving of m2m data as a function.
48     def save_m2m():
49         opts = instance._meta
50         cleaned_data = form.cleaned_data
51         for f in opts.many_to_many:
52             if fields and f.name not in fields:
53                 continue
54             if f.name in cleaned_data:
55                 f.save_form_data(instance, cleaned_data[f.name])
56     if commit:
57         # If we are committing, save the instance and the m2m data immediately.
58         instance.save()
59         save_m2m()
60     else:
61         # We're not committing. Add a method to the form to allow deferred
62         # saving of m2m data.
63         form.save_m2m = save_m2m
64     return instance
65
66 def make_model_save(model, fields, fail_message):
67     """Returns the save() method for a Form."""
68     def save(self, commit=True):
69         return save_instance(self, model(), fields, fail_message, commit)
70     return save
71
72 def make_instance_save(instance, fields, fail_message):
73     """Returns the save() method for a Form."""
74     def save(self, commit=True):
75         return save_instance(self, instance, fields, fail_message, commit)
76     return save
77
78 def form_for_model(model, form=BaseForm, fields=None,
79                    formfield_callback=lambda f: f.formfield()):
80     """
81     Returns a Form class for the given Django model class.
82
83     Provide ``form`` if you want to use a custom BaseForm subclass.
84
85     Provide ``formfield_callback`` if you want to define different logic for
86     determining the formfield for a given database field. It's a callable that
87     takes a database Field instance and returns a form Field instance.
88     """
89     warn("form_for_model is deprecated. Use ModelForm instead.",
90         PendingDeprecationWarning, stacklevel=3)
91     opts = model._meta
92     field_list = []
93     for f in opts.fields + opts.many_to_many:
94         if not f.editable:
95             continue
96         if fields and not f.name in fields:
97             continue
98         formfield = formfield_callback(f)
99         if formfield:
100             field_list.append((f.name, formfield))
101     base_fields = SortedDict(field_list)
102     return type(opts.object_name + 'Form', (form,),
103         {'base_fields': base_fields, '_model': model,
104          'save': make_model_save(model, fields, 'created')})
105
106 def form_for_instance(instance, form=BaseForm, fields=None,
107                       formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):
108     """
109     Returns a Form class for the given Django model instance.
110
111     Provide ``form`` if you want to use a custom BaseForm subclass.
112
113     Provide ``formfield_callback`` if you want to define different logic for
114     determining the formfield for a given database field. It's a callable that
115     takes a database Field instance, plus **kwargs, and returns a form Field
116     instance with the given kwargs (i.e. 'initial').
117     """
118     warn("form_for_instance is deprecated. Use ModelForm instead.",
119         PendingDeprecationWarning, stacklevel=3)
120     model = instance.__class__
121     opts = model._meta
122     field_list = []
123     for f in opts.fields + opts.many_to_many:
124         if not f.editable:
125             continue
126         if fields and not f.name in fields:
127             continue
128         current_value = f.value_from_object(instance)
129         formfield = formfield_callback(f, initial=current_value)
130         if formfield:
131             field_list.append((f.name, formfield))
132     base_fields = SortedDict(field_list)
133     return type(opts.object_name + 'InstanceForm', (form,),
134         {'base_fields': base_fields, '_model': model,
135          'save': make_instance_save(instance, fields, 'changed')})
136
137 def form_for_fields(field_list):
138     """
139     Returns a Form class for the given list of Django database field instances.
140     """
141     fields = SortedDict([(f.name, f.formfield())
142                          for f in field_list if f.editable])
143     return type('FormForFields', (BaseForm,), {'base_fields': fields})
144
145
146 # ModelForms #################################################################
147
148 def model_to_dict(instance, fields=None, exclude=None):
149     """
150     Returns a dict containing the data in ``instance`` suitable for passing as
151     a Form's ``initial`` keyword argument.
152
153     ``fields`` is an optional list of field names. If provided, only the named
154     fields will be included in the returned dict.
155
156     ``exclude`` is an optional list of field names. If provided, the named
157     fields will be excluded from the returned dict, even if they are listed in
158     the ``fields`` argument.
159     """
160     # avoid a circular import
161     from django.db.models.fields.related import ManyToManyField
162     opts = instance._meta
163     data = {}
164     for f in opts.fields + opts.many_to_many:
165         if not f.editable:
166             continue
167         if fields and not f.name in fields:
168             continue
169         if exclude and f.name in exclude:
170             continue
171         if isinstance(f, ManyToManyField):
172             # If the object doesn't have a primry key yet, just use an empty
173             # list for its m2m fields. Calling f.value_from_object will raise
174             # an exception.
175             if instance.pk is None:
176                 data[f.name] = []
177             else:
178                 # MultipleChoiceWidget needs a list of pks, not object instances.
179                 data[f.name] = [obj.pk for obj in f.value_from_object(instance)]
180         else:
181             data[f.name] = f.value_from_object(instance)
182     return data
183
184 def fields_for_model(model, fields=None, exclude=None, formfield_callback=lambda f: f.formfield()):
185     """
186     Returns a ``SortedDict`` containing form fields for the given model.
187
188     ``fields`` is an optional list of field names. If provided, only the named
189     fields will be included in the returned fields.
190
191     ``exclude`` is an optional list of field names. If provided, the named
192     fields will be excluded from the returned fields, even if they are listed
193     in the ``fields`` argument.
194     """
195     # TODO: if fields is provided, it would be nice to return fields in that order
196     field_list = []
197     opts = model._meta
198     for f in opts.fields + opts.many_to_many:
199         if not f.editable:
200             continue
201         if fields and not f.name in fields:
202             continue
203         if exclude and f.name in exclude:
204             continue
205         formfield = formfield_callback(f)
206         if formfield:
207             field_list.append((f.name, formfield))
208     return SortedDict(field_list)
209
210 class ModelFormOptions(object):
211     def __init__(self, options=None):
212         self.model = getattr(options, 'model', None)
213         self.fields = getattr(options, 'fields', None)
214         self.exclude = getattr(options, 'exclude', None)
215
216
217 class ModelFormMetaclass(type):
218     def __new__(cls, name, bases, attrs):
219         formfield_callback = attrs.pop('formfield_callback',
220                 lambda f: f.formfield())
221         try:
222             parents = [b for b in bases if issubclass(b, ModelForm)]
223         except NameError:
224             # We are defining ModelForm itself.
225             parents = None
226         new_class = super(ModelFormMetaclass, cls).__new__(cls, name, bases,
227                 attrs)
228         if not parents:
229             return new_class
230
231         if 'media' not in attrs:
232             new_class.media = media_property(new_class)
233         declared_fields = get_declared_fields(bases, attrs, False)
234         opts = new_class._meta = ModelFormOptions(getattr(new_class, 'Meta', None))
235         if opts.model:
236             # If a model is defined, extract form fields from it.
237             fields = fields_for_model(opts.model, opts.fields,
238                                       opts.exclude, formfield_callback)
239             # Override default model fields with any custom declared ones
240             # (plus, include all the other declared fields).
241             fields.update(declared_fields)
242         else:
243             fields = declared_fields
244         new_class.declared_fields = declared_fields
245         new_class.base_fields = fields
246         return new_class
247
248 class BaseModelForm(BaseForm):
249     def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
250                  initial=None, error_class=ErrorList, label_suffix=':',
251                  empty_permitted=False, instance=None):
252         opts = self._meta
253         if instance is None:
254             # if we didn't get an instance, instantiate a new one
255             self.instance = opts.model()
256             object_data = {}
257         else:
258             self.instance = instance
259             object_data = model_to_dict(instance, opts.fields, opts.exclude)
260         # if initial was provided, it should override the values from instance
261         if initial is not None:
262             object_data.update(initial)
263         BaseForm.__init__(self, data, files, auto_id, prefix, object_data,
264                           error_class, label_suffix, empty_permitted)
265
266     def save(self, commit=True):
267         """
268         Saves this ``form``'s cleaned_data into model instance
269         ``self.instance``.
270
271         If commit=True, then the changes to ``instance`` will be saved to the
272         database. Returns ``instance``.
273         """
274         if self.instance.pk is None:
275             fail_message = 'created'
276         else:
277             fail_message = 'changed'
278         return save_instance(self, self.instance, self._meta.fields, fail_message, commit)
279
280 class ModelForm(BaseModelForm):
281     __metaclass__ = ModelFormMetaclass
282
283 def modelform_factory(model, form=ModelForm, fields=None, exclude=None,
284                        formfield_callback=lambda f: f.formfield()):
285     # HACK: we should be able to construct a ModelForm without creating
286     # and passing in a temporary inner class
287     class Meta:
288         pass
289     setattr(Meta, 'model', model)
290     setattr(Meta, 'fields', fields)
291     setattr(Meta, 'exclude', exclude)
292     class_name = model.__name__ + 'Form'
293     return ModelFormMetaclass(class_name, (form,), {'Meta': Meta,
294                               'formfield_callback': formfield_callback})
295
296
297 # ModelFormSets ##############################################################
298
299 class BaseModelFormSet(BaseFormSet):
300     """
301     A ``FormSet`` for editing a queryset and/or adding new objects to it.
302     """
303     model = None
304
305     def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
306                  queryset=None, **kwargs):
307         self.queryset = queryset
308         defaults = {'data': data, 'files': files, 'auto_id': auto_id, 'prefix': prefix}
309         if self._max_form_count > 0:
310             qs = self.get_queryset()[:self._max_form_count]
311         else:
312             qs = self.get_queryset()
313         defaults['initial'] = [model_to_dict(obj) for obj in qs]
314         defaults.update(kwargs)
315         super(BaseModelFormSet, self).__init__(**defaults)
316
317     def get_queryset(self):
318         if self.queryset is not None:
319             return self.queryset
320         return self.model._default_manager.get_query_set()
321
322     def save_new(self, form, commit=True):
323         """Saves and returns a new model instance for the given form."""
324         return save_instance(form, self.model(), commit=commit)
325
326     def save_existing(self, form, instance, commit=True):
327         """Saves and returns an existing model instance for the given form."""
328         return save_instance(form, instance, commit=commit)
329
330     def save(self, commit=True):
331         """Saves model instances for every form, adding and changing instances
332         as necessary, and returns the list of instances.
333         """
334         if not commit:
335             self.saved_forms = []
336             def save_m2m():
337                 for form in self.saved_forms:
338                     form.save_m2m()
339             self.save_m2m = save_m2m
340         return self.save_existing_objects(commit) + self.save_new_objects(commit)
341
342     def save_existing_objects(self, commit=True):
343         self.changed_objects = []
344         self.deleted_objects = []
345         if not self.get_queryset():
346             return []
347
348         # Put the objects from self.get_queryset into a dict so they are easy to lookup by pk
349         existing_objects = {}
350         for obj in self.get_queryset():
351             existing_objects[obj.pk] = obj
352         saved_instances = []
353         for form in self.initial_forms:
354             obj = existing_objects[form.cleaned_data[self.model._meta.pk.attname]]
355             if self.can_delete and form.cleaned_data[DELETION_FIELD_NAME]:
356                 self.deleted_objects.append(obj)
357                 obj.delete()
358             else:
359                 if form.changed_data:
360                     self.changed_objects.append((obj, form.changed_data))
361                     saved_instances.append(self.save_existing(form, obj, commit=commit))
362                     if not commit:
363                         self.saved_forms.append(form)
364         return saved_instances
365
366     def save_new_objects(self, commit=True):
367         self.new_objects = []
368         for form in self.extra_forms:
369             if not form.has_changed():
370                 continue
371             # If someone has marked an add form for deletion, don't save the
372             # object.
373             if self.can_delete and form.cleaned_data[DELETION_FIELD_NAME]:
374                 continue
375             self.new_objects.append(self.save_new(form, commit=commit))
376             if not commit:
377                 self.saved_forms.append(form)
378         return self.new_objects
379
380     def add_fields(self, form, index):
381         """Add a hidden field for the object's primary key."""
382         self._pk_field_name = self.model._meta.pk.attname
383         form.fields[self._pk_field_name] = IntegerField(required=False, widget=HiddenInput)
384         super(BaseModelFormSet, self).add_fields(form, index)
385
386 def modelformset_factory(model, form=ModelForm, formfield_callback=lambda f: f.formfield(),
387                          formset=BaseModelFormSet,
388                          extra=1, can_delete=False, can_order=False,
389                          max_num=0, fields=None, exclude=None):
390     """
391     Returns a FormSet class for the given Django model class.
392     """
393     form = modelform_factory(model, form=form, fields=fields, exclude=exclude,
394                              formfield_callback=formfield_callback)
395     FormSet = formset_factory(form, formset, extra=extra, max_num=max_num,
396                               can_order=can_order, can_delete=can_delete)
397     FormSet.model = model
398     return FormSet
399
400
401 # InlineFormSets #############################################################
402
403 class BaseInlineFormset(BaseModelFormSet):
404     """A formset for child objects related to a parent."""
405     def __init__(self, data=None, files=None, instance=None, save_as_new=False):
406         from django.db.models.fields.related import RelatedObject
407         self.instance = instance
408         self.save_as_new = save_as_new
409         # is there a better way to get the object descriptor?
410         self.rel_name = RelatedObject(self.fk.rel.to, self.model, self.fk).get_accessor_name()
411         super(BaseInlineFormset, self).__init__(data, files, prefix=self.rel_name)
412    
413     def _construct_forms(self):
414         if self.save_as_new:
415             self._total_form_count = self._initial_form_count
416             self._initial_form_count = 0
417         super(BaseInlineFormset, self)._construct_forms()
418
419     def get_queryset(self):
420         """
421         Returns this FormSet's queryset, but restricted to children of
422         self.instance
423         """
424         kwargs = {self.fk.name: self.instance}
425         return self.model._default_manager.filter(**kwargs)
426
427     def save_new(self, form, commit=True):
428         kwargs = {self.fk.get_attname(): self.instance.pk}
429         new_obj = self.model(**kwargs)
430         return save_instance(form, new_obj, commit=commit)
431
432 def _get_foreign_key(parent_model, model, fk_name=None):
433     """
434     Finds and returns the ForeignKey from model to parent if there is one.
435     If fk_name is provided, assume it is the name of the ForeignKey field.
436     """
437     # avoid circular import
438     from django.db.models import ForeignKey
439     opts = model._meta
440     if fk_name:
441         fks_to_parent = [f for f in opts.fields if f.name == fk_name]
442         if len(fks_to_parent) == 1:
443             fk = fks_to_parent[0]
444             if not isinstance(fk, ForeignKey) or fk.rel.to != parent_model:
445                 raise Exception("fk_name '%s' is not a ForeignKey to %s" % (fk_name, parent_model))
446         elif len(fks_to_parent) == 0:
447             raise Exception("%s has no field named '%s'" % (model, fk_name))
448     else:
449         # Try to discover what the ForeignKey from model to parent_model is
450         fks_to_parent = [f for f in opts.fields if isinstance(f, ForeignKey) and f.rel.to == parent_model]
451         if len(fks_to_parent) == 1:
452             fk = fks_to_parent[0]
453         elif len(fks_to_parent) == 0:
454             raise Exception("%s has no ForeignKey to %s" % (model, parent_model))
455         else:
456             raise Exception("%s has more than 1 ForeignKey to %s" % (model, parent_model))
457     return fk
458
459
460 def inlineformset_factory(parent_model, model, form=ModelForm,
461                           formset=BaseInlineFormset, fk_name=None,
462                           fields=None, exclude=None,
463                           extra=3, can_order=False, can_delete=True, max_num=0,
464                           formfield_callback=lambda f: f.formfield()):
465     """
466     Returns an ``InlineFormset`` for the given kwargs.
467
468     You must provide ``fk_name`` if ``model`` has more than one ``ForeignKey``
469     to ``parent_model``.
470     """
471     fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
472     # let the formset handle object deletion by default
473    
474     if exclude is not None:
475         exclude.append(fk.name)
476     else:
477         exclude = [fk.name]
478     FormSet = modelformset_factory(model, form=form,
479                                     formfield_callback=formfield_callback,
480                                     formset=formset,
481                                     extra=extra, can_delete=can_delete, can_order=can_order,
482                                     fields=fields, exclude=exclude, max_num=max_num)
483     FormSet.fk = fk
484     return FormSet
485
486
487 # Fields #####################################################################
488
489 class ModelChoiceIterator(object):
490     def __init__(self, field):
491         self.field = field
492         self.queryset = field.queryset
493
494     def __iter__(self):
495