nocoder
nocoder

Reputation: 23

Django - is it required to use/overwrite form_valid() when using CBV?

I'm using the below class based view in Django in order to be able to create/insert new object in the database which works:

class AddAreaMapView(CreateView):
    model = AreaMap
    fields = ['fCityCode',
              'fCountyCode', 'fCountryCode', ]
    template_name = 'myapp/blank.html'
    success_url = '/'

However, I've seen that there is recommended to use form_valid() method together with the CreateView. Why is it required to overwrite it since Django is already doing that? Is a missing piece of information and I would appreciate if anyone could provide a relevant answer. Thanks!

Upvotes: 2

Views: 76

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477437

Why is it required to overwrite it since Django is already doing that?

It is not. In the Django documentation, the example [Django-doc] does not contain an override for the form_valid.

The form_valid that is used is the one provided by the ModelFormMixin [Django-doc]. For the form_valid method [Django-doc] it will:

Saves the form instance, sets the current object for the view, and redirects to get_success_url().

The get_success_url() method [Django-doc] will:

Determine the URL to redirect to when the form is successfully validated. Returns django.views.generic.edit.ModelFormMixin.success_url if it is provided; otherwise, attempts to use the get_absolute_url() of the object.

So if you provide a success_url, it will redirect to that url. If you do not provide a success_url (or override the get_success_url method), it will aim to take the get_absolute_url() [Django-doc] of the object.

Upvotes: 1

Related Questions