Login

Form and ModelForm inheritance DRY

Author:
evilclay
Posted:
June 3, 2013
Language:
Python
Version:
1.4
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.