Create user and user profile in CreateView using single Formset without using post_save signal

Before we begin I am using Python 3.5.2 and Django 1.11.3 and basic knowledge of Django models, forms and views is required, so let’s begin. When I first started learning Django one of the things I needed to do was create a user and a user profile at the same time in the same view using a single form. So let’s start from the beginning with our models:

1.) Let’s start with line 12, here we are overriding the form_valid() method of the CreateView. We override this method when we want want to do some extra processing after the form has been validated and cleaned.

2.) On line 13, we use the form object and store it in a form dictionary inside of our context variable, “c”, for later use by the render function.

3.) On line 14, we are retrieving the form data by using form.save(commit=False) without sending it to the database so we can use for form.cleaned_data dictionary to get the extra fields from our formset so we can populate them later. On lines 16-19 we are getting the extra form fields via form.cleaned data.

4.) On lines 20-22 we are verifying if the passwords the user supplied are indeed a match, if not then we send an error message via messages.error() function, then we render the original form.

5.) If the passwords do match then on lines 23-24 we are setting the password via the set_password() method, and saving the user model to the database via the save() method.

6) On line 27, now that we have successfully saved the user we can now use the user object just created to create a UserProfile object with the extra form fields captured by the form. 7.) And lastly on line 29, we return the HTTP response.

And that’s it, that’s how I was able to create a user and user profile within a single Django CreateView and Formset. Please keep in mind that you can also do this by using a post_save signal, which I will be writing another article on that here in the near future. Thanks, and please comment below if you have any questions.