Django Django Class Based Views: Example of CreateView


Example

With the Class Based generic Views, it is very simple and easy to create the CRUD views from our models. Often, the built in Django admin is not enough or not preferred and we need to roll our own CRUD views. The CBVs can be very handy in such cases.

The CreateView class needs 3 things - a model, the fields to use and success url.

Example:

from django.views.generic import CreateView 
from .models import Campaign

class CampaignCreateView(CreateView):
    model = Campaign
    fields = ('title', 'description')
    
    success_url = "/campaigns/list"

Once the creation success, the user is redirected to success_url. We can also define a method get_success_url instead and use reverse or reverse_lazy to get the success url.

Now, we need to create a template for this view. The template should be named in the format <app name>/<model name>_form.html. The model name must be in lower caps. For example, if my app name is dashboard, then for the above create view, I need to create a template named dashboard/campaign_form.html.

In the template, a form variable would contain the form. Here's a sample code for the template:

<form action="" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save" />
</form>            

Now it's time to add the view to our url patterns.

url('^campaign/new/$', CampaignCreateView.as_view(), name='campaign_new'),

If we visit the URL, we should see a form with the fields we chose. When we submit, it will try to create a new instance of the model with the data and save it. On success, the user will be redirected to the success url. On errors, the form will be displayed again with the error messages.