praveen kumar
praveen kumar

Reputation: 24

Best way to create forms in django

I am learning django, when it comes to creating forms, there are three ways to create a forms in django,

  1. create forms in html
  2. Forms api
  3. ModelForm

what method should i use for creating forums, are there any advantage of using one instead of other, or all are equal?

Upvotes: 0

Views: 257

Answers (1)

Nicky
Nicky

Reputation: 316

I would say that ModelForm is the best way to go in terms of rapid development. If you were to create raw forms with HTML, you would have to spend extra time validating the user's inputs and it would be prone to bugs.

ModelForm inherits a model, and will try to apply the same validators that are on your model to your form. Thus, your form's inputs will be valid to insert into your model's table.

If you want to see this in action, create a ModelForm which points to a specific model:

class ExampleModelForm(ModelForm):
    class Meta:
    model = your_model

Then enter the interactive shell and import your ModelForms.

python manage.py shell

Instantiate your form

form = ExampleModelForm()

Then see the validators already active on the form:

repr(form)

You'll see that your form's validation matches pretty closely to your model. You can't get this out-of-the-box with the other specified methods.

Upvotes: 2

Related Questions