cms_mgr
cms_mgr

Reputation: 2017

What method creates the object in a Django class-based CreateView?

This answer shows how to use get_or_create with django forms. It will work fine for me because the model in question has no unique constraints other than the pk. But it looks to me like it's not using the generic CreateView, which I'd like to stick to if I can.

I presume the best way to emulate this in a CreateView is to override whichever method actually saves an object to the database but I can't find where that's happening in the source code. Am I missing something obvious or have I misunderstood how this is working?

Upvotes: 0

Views: 467

Answers (1)

Alasdair
Alasdair

Reputation: 308779

CreateView inherits from ModelFormMixin. Override the form_valid method to change the behaviour when the form is valid.

You can see the code for the form_valid method on GitHub. The default behaviour is described in the docs as:

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

Upvotes: 1

Related Questions