Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django FormView vs CreateView

What is difference between Django FormView and CreateView?

Only diffrence I see, FormView require ModelForm but CreateView doesn't.

Otherwise both does same thing creating an object.

like image 219
Vaibhav Mule Avatar asked Apr 09 '16 05:04

Vaibhav Mule


People also ask

When to use FormView Django?

FormView should be used when you need a form on the page and want to perform certain action when a valid form is submitted. eg: Having a contact us form and sending an email on form submission. CreateView would probably be a better choice if you want to insert a model instance in database on form submission.

What is Django FormView?

FormView refers to a view (logic) to display and verify a Django Form. For example, a form to register users at Geeksforgeeks. Class-based views provide an alternative way to implement views as Python objects instead of functions.

What does CreateView do in Django?

CreateView. A view that displays a form for creating an object, redisplaying the form with validation errors (if there are any) and saving the object. This view inherits methods and attributes from the following views: django.

What is Form_class in Django?

Hi Christopher 'form_class' is used in Django Class Based to depict the Form to be used in a class based view. See example in the docs: https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-editing/


1 Answers

From Django-docs:

FormView:

A view that displays a form. On error, redisplays the form with validation errors; on success, redirects to a new URL.

It can be used for various purposes and is not restricted to creating objects. A nice example would be using it as a contact form and sending emails without creating records in database.

CreateView:

A view that displays a form for creating an object, redisplaying the form with validation errors (if there are any) and saving the object.

The sole purpose of this generic view is to create objects. But it is not limited to creating objects. You can send emails from this view too (just like FormView)

If your FormView creates model objects, it is best to use CreateView and not creating a modelform, that's what generic views are for, reducing repetition.

like image 179
v1k45 Avatar answered Sep 19 '22 15:09

v1k45