User Registration with UserCreationForm
A snippet showing how to create a simple user registration form with UserCreationForm.
# views.py
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
def register_view(request):
form = UserCreationForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('login')
return render(request, 'register.html', {'form': form})
# templates/register.html
<h2>Register</h2>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign Up</button>
</form>
Explanation:
-
UserCreationFormis a built-in Django form that handles username and password validation for new users. -
We use
form.save()to create the user if the form is valid. - After registration, the user is redirected to the login page.
-
{{ form.as_p }}renders all form fields wrapped in paragraph tags automatically.
- Category Authentication & Authorization
- Total Views 852
- Last Modified 15 September, 2025
- Tags #signup #registration #forms #auth
Previous snippet
Restrict Access with LoginRequiredMixin (CBV)
Next snippet