Login

Form and ModelForm inheritance DRY

Author:
evilclay
Posted:
June 3, 2013
Language:
Python
Version:
1.4
Tags:
form inheritance
Score:
-1 (after 1 ratings)

Modelform cant inhertit from forms. To solve this issue, split thing you wanto to inherit into filed definition and functionality definition. For modelform use the base_fields.update method as mentioned in the code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class MyCommonFiledsForm(Form):
     timestamp = forms.IntegerField(widget=forms.HiddenInput)
     ... more fileds nothig else (no methods)

class MyCommonFiledsFormMixin(object):

    #  just an example of init method
    def __init__(self, *args, **kwargs):
        initial = kwargs.get("initial", {})
        initial.update(self.generate_security_data())
        kwargs["initial"] = initial
        super(MyCommonFiledsFormMixin, self).__init__(*args, **kwargs)

    # just an example of a clean method
    def clean_timestamp(self):
        """Make sure the timestamp isn't too far (> 2 hours) in the past or too close (< 5 seg)."""
        ts = self.cleaned_data["timestamp"]
        difference = time.time() - ts
        if difference > (2 * 60 * 60) or difference < 5:
            raise forms.ValidationError(_("Timestamp check failed"))
        return ts


# now for form use like this
class ContactForm(MyCommonFiledsFormMixin, MyCommonFiledsForm):
	sender = forms.EmailField(label=_("Your email address"), initial="@")
        ...other new fields and methods


# now for model form use like this
class CommentModelForm(MyCommonFiledsFormMixin, ModelForm):

    class Meta:
        model = EntryComment # just as example, use your own model...

# this is importat for modelform
CommentModelForm.base_fields.update(MyCommonFiledsForm.base_fields)

More like this

  1. Multiple inheritance of newforms and modelforms by simon 7 years ago
  2. unique validation for ModelForm by whiskybar 7 years, 1 month ago
  3. Embedded inline formsets in ModelForm by stan 4 years, 6 months ago
  4. ModelForm Class saving m2m by ckarrie2 3 years, 6 months ago
  5. Automating URLs by jorjun 5 years, 10 months ago

Comments

Please login first before commenting.