~ubuntu-branches/ubuntu/oneiric/python-django/oneiric-201108291626

« back to all changes in this revision

Viewing changes to django/forms/models.py

  • Committer: Bazaar Package Importer
  • Author(s): Jamie Strandboge
  • Date: 2010-10-12 11:34:35 UTC
  • mfrom: (1.1.12 upstream) (29.1.1 maverick-security)
  • Revision ID: james.westby@ubuntu.com-20101012113435-yy57c8tx6g9anf3e
Tags: 1.2.3-1ubuntu0.1
* SECURITY UPDATE: XSS in CSRF protections. New upstream release
  - CVE-2010-3082
* debian/patches/01_disable_url_verify_regression_tests.diff:
  - updated to disable another test that fails without internet connection
  - patch based on work by Kai Kasurinen and Krzysztof Klimonda
* debian/control: don't Build-Depends on locales-all, which doesn't exist
  in maverick

Show diffs side-by-side

added added

removed removed

Lines of Context:
150
150
            data[f.name] = f.value_from_object(instance)
151
151
    return data
152
152
 
153
 
def fields_for_model(model, fields=None, exclude=None, widgets=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):
 
153
def fields_for_model(model, fields=None, exclude=None, widgets=None, formfield_callback=None):
154
154
    """
155
155
    Returns a ``SortedDict`` containing form fields for the given model.
156
156
 
175
175
            kwargs = {'widget': widgets[f.name]}
176
176
        else:
177
177
            kwargs = {}
178
 
        formfield = formfield_callback(f, **kwargs)
 
178
 
 
179
        if formfield_callback is None:
 
180
            formfield = f.formfield(**kwargs)
 
181
        elif not callable(formfield_callback):
 
182
            raise TypeError('formfield_callback must be a function or callable')
 
183
        else:
 
184
            formfield = formfield_callback(f, **kwargs)
 
185
 
179
186
        if formfield:
180
187
            field_list.append((f.name, formfield))
181
188
        else:
198
205
 
199
206
class ModelFormMetaclass(type):
200
207
    def __new__(cls, name, bases, attrs):
201
 
        formfield_callback = attrs.pop('formfield_callback',
202
 
                lambda f, **kwargs: f.formfield(**kwargs))
 
208
        formfield_callback = attrs.pop('formfield_callback', None)
203
209
        try:
204
210
            parents = [b for b in bases if issubclass(b, ModelForm)]
205
211
        except NameError:
376
382
    __metaclass__ = ModelFormMetaclass
377
383
 
378
384
def modelform_factory(model, form=ModelForm, fields=None, exclude=None,
379
 
                       formfield_callback=lambda f: f.formfield()):
 
385
                       formfield_callback=None):
380
386
    # Create the inner Meta class. FIXME: ideally, we should be able to
381
387
    # construct a ModelForm without creating and passing in a temporary
382
388
    # inner class.
658
664
            form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_value, required=False, widget=HiddenInput)
659
665
        super(BaseModelFormSet, self).add_fields(form, index)
660
666
 
661
 
def modelformset_factory(model, form=ModelForm, formfield_callback=lambda f: f.formfield(),
 
667
def modelformset_factory(model, form=ModelForm, formfield_callback=None,
662
668
                         formset=BaseModelFormSet,
663
669
                         extra=1, can_delete=False, can_order=False,
664
670
                         max_num=None, fields=None, exclude=None):
813
819
                          formset=BaseInlineFormSet, fk_name=None,
814
820
                          fields=None, exclude=None,
815
821
                          extra=3, can_order=False, can_delete=True, max_num=None,
816
 
                          formfield_callback=lambda f: f.formfield()):
 
822
                          formfield_callback=None):
817
823
    """
818
824
    Returns an ``InlineFormSet`` for the given kwargs.
819
825
 
906
912
        return len(self.queryset)
907
913
 
908
914
    def choice(self, obj):
909
 
        if self.field.to_field_name:
910
 
            key = obj.serializable_value(self.field.to_field_name)
911
 
        else:
912
 
            key = obj.pk
913
 
        return (key, self.field.label_from_instance(obj))
914
 
 
 
915
        return (self.field.prepare_value(obj), self.field.label_from_instance(obj))
915
916
 
916
917
class ModelChoiceField(ChoiceField):
917
918
    """A ChoiceField whose choices are a model QuerySet."""
971
972
            return self._choices
972
973
 
973
974
        # Otherwise, execute the QuerySet in self.queryset to determine the
974
 
        # choices dynamically. Return a fresh QuerySetIterator that has not been
975
 
        # consumed. Note that we're instantiating a new QuerySetIterator *each*
 
975
        # choices dynamically. Return a fresh ModelChoiceIterator that has not been
 
976
        # consumed. Note that we're instantiating a new ModelChoiceIterator *each*
976
977
        # time _get_choices() is called (and, thus, each time self.choices is
977
978
        # accessed) so that we can ensure the QuerySet has not been consumed. This
978
979
        # construct might look complicated but it allows for lazy evaluation of
981
982
 
982
983
    choices = property(_get_choices, ChoiceField._set_choices)
983
984
 
 
985
    def prepare_value(self, value):
 
986
        if hasattr(value, '_meta'):
 
987
            if self.to_field_name:
 
988
                return value.serializable_value(self.to_field_name)
 
989
            else:
 
990
                return value.pk
 
991
        return super(ModelChoiceField, self).prepare_value(value)
 
992
 
984
993
    def to_python(self, value):
985
994
        if value in EMPTY_VALUES:
986
995
            return None
1030
1039
            if force_unicode(val) not in pks:
1031
1040
                raise ValidationError(self.error_messages['invalid_choice'] % val)
1032
1041
        return qs
 
1042
 
 
1043
    def prepare_value(self, value):
 
1044
        if hasattr(value, '__iter__'):
 
1045
            return [super(ModelMultipleChoiceField, self).prepare_value(v) for v in value]
 
1046
        return super(ModelMultipleChoiceField, self).prepare_value(value)