Which of these two ways is the best way to make forms?

Like this where you directly assign a form’s attributes and stuff (in forms.py)

class ContactForm(forms.Form):
    name= forms.CharField(max_length=500, label="Name")
    email= forms.EmailField(max_length=254, label="Email")
    comment= forms.CharField(label='',widget=forms.Textarea(attrs={'placeholder': 'Enter your message here'}))

Or like this where you assign its attributes and stuff in models.py and import it in forms.py

class MessageForm(forms.ModelForm):

    class Meta:
        model = Message
        fields = '__all__'

In my opinion there’s not really a best way, they’re both tools for accomplishing the same task.

Django docs say it provides ModelForm as a helper class that lets you create a Form class from a Django model.

In some case you may need to create a form without relying on an existing model. There you’ll need to use simple forms. Also in the case you need to deeply customize your form it may be better to create it from scratch.

1 Like

Most importantly, don’t confuse the fields you define in a model with the fields defined in a form.

When you create a model form, form fields are being created, just “automatically” and “behind the scenes”. You still have two separate sets of fields, with different characteristics and behaviors.


1 Like