Ticket #3632: forms.py.3.diff

File forms.py.3.diff, 2.6 KB (added by empty <mtrier@…>, 7 years ago)

Patch with tests

  • django/newforms/forms.py

     
    3838            if hasattr(base, 'base_fields'):
    3939                fields = base.base_fields.items() + fields
    4040
    41         attrs['base_fields'] = SortedDict(fields)
     41        # preserve initial values
     42        base_fields = SortedDict(fields)
     43        if attrs.get('base_fields'):
     44            base_fields = base_fields.copy()
     45            for k, v in attrs.get('base_fields').items():
     46                if k in base_fields:
     47                    base_fields[k].initial = v.initial
     48        attrs['base_fields'] = base_fields
    4249        return type.__new__(cls, name, bases, attrs)
    4350
    4451class BaseForm(StrAndUnicode):
  • tests/modeltests/model_forms/models.py

     
    665665<option value="mt">Manual</option>
    666666<option value="cvt">CVT</option>
    667667</select><br />Leave empty if not applicable.</td></tr>
     668
     669Use form_for_instance to create a Form from a model instance. This time
     670pass a form class definition in the form option and be sure the form subclasses
     671BaseForm.  Verify that initial values are set properly.
     672>>> class CategoryForm(BaseForm):
     673...     def say_hello(self):
     674...         print 'hello'
     675>>> domestic = Category(name='Domestic Cars')
     676>>> form = form_for_instance(domestic, form=CategoryForm)
     677>>> f = form()
     678>>> f.say_hello()
     679hello
     680>>> print f
     681<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" value="Domestic Cars" maxlength="20" /></td></tr>
     682<tr><th><label for="id_slug">Slug:</label></th><td><input id="id_slug" type="text" name="slug" maxlength="20" /></td></tr>
     683<tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>
     684
     685Use form_for_instance to create a Form from a model instance. This time
     686pass a form class definition in the form option.  Verify that initial
     687values are set properly.
     688>>> class CategoryForm(Form):
     689...     name = CharField(max_length=20)
     690...     
     691...     def say_hello(self):
     692...         print 'hello'
     693>>> domestic = Category(name='Domestic Cars')
     694>>> form = form_for_instance(domestic, form=CategoryForm)
     695>>> f = form()
     696>>> f.say_hello()
     697hello
     698>>> print f
     699<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" value="Domestic Cars" maxlength="20" /></td></tr>
    668700"""}
Back to Top