Episode 20 of 32
Saving Users
Handle the POST request from the signup form — validate the data, create the user in the database, and redirect on success.
Saving Users
The form is rendered on GET. Now let us handle the POST request — validate the submitted data and save the new user to the database.
Updated Signup View
# accounts/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
def signup_view(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('articles:list')
else:
form = UserCreationForm()
return render(request, 'accounts/signup.html', {
'form': form
})
The Flow
GET /accounts/signup/
→ Create empty form → render template
POST /accounts/signup/
→ Create form with POST data
→ Valid? → Save user → redirect to articles
→ Invalid? → Re-render form with errors
How Validation Works
form = UserCreationForm(request.POST)
if form.is_valid():
# Passwords match, username unique, meets requirements
form.save() # Creates the User in the database
is_valid() checks that passwords match, the username is not taken, the password meets strength requirements. If validation fails, form.errors contains the error messages, and re-rendering the template displays them.
Displaying Errors
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<!-- Errors are shown automatically when the form re-renders -->
<button type="submit">Create Account</button>
</form>
Key Takeaways
- Check
request.methodto distinguish between GET (display) and POST (submit) UserCreationForm(request.POST)binds submitted data to the formform.is_valid()validates all fields;form.save()creates the user- On validation failure, re-render the form — errors display automatically