[Django]-Good practice to make Django forms.py DRY

2👍

Answer made by user2032220 is good. Also instead of using EMAIL_FIELD, it’s better to extend forms.EmailField class and apply your own default values for class:

class EmailField(forms.EmailField):
    """Your custom EmailField with best set of default kwargs"""
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('label', 'Adresse e-mail')
        kwargs.setdefault('widget', forms.TextInput())
        kwargs.setdefault('error_messages', DICT_ERROR)
        return super(EmailField, self).__init__(*args, **kwargs)


class BaseForm(forms.Form):
    email = EmailField()
    password = forms.CharField()

    class Meta:
        abstract=True

##Inherit BaseForm
class SignUpForm(BaseForm):
    ## Other attributes

class ContactForm(forms.Form):
    # Easy way of changing just one parameter
    email = EmailField(label='Your email')

2👍

Here’s one way you can do it.

class BaseForm(forms.Form):
    email = forms.EmailField()
    password = forms.CharField()

    class Meta:
        abstract=True

##Inherit BaseForm
class SignUpForm(BaseForm):
    ## Other attributes

Leave a comment