David Dahan
David Dahan

Reputation: 11172

Good practice to make Django forms.py DRY

I had an idea about how to make my forms.py DRY but since I have never seen it elsewhere before, I'm questioning myself.

The whole purpose is to re-use form fields in different forms.

Here is what I'd like to do:

File: form_fields.py

EMAIL_FIELD = forms.EmailField(
    label="Adresse e-mail",
    widget=forms.TextInput(),
    error_messages=DICT_ERROR)

PASSWORD_FIELD = ...

File: forms.py

class SignupForm(forms.Form):
    email = EMAIL_FIELD
    pwd = PASSWORD_FIELD
    ... etc.

class SigninForm(forms.Form):
    email = EMAIL_FIELD
    pwd = PASSWORD_FIELD

Is it OK to you? If it's not, what do you suggest to make a good "architecture" of a forms.py file which can grow a lot in my case?

In addition, I'm asking myself if I'm supposed to create only 1 field variable for fields that have same characteristics (e.g. first name and last name). In that case, how do you handle the different labels?

Thanks.

Upvotes: 3

Views: 125

Answers (2)

daniula
daniula

Reputation: 7028

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')

Upvotes: 2

pynovice
pynovice

Reputation: 7752

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

Upvotes: 2

Related Questions