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:
  • UserCreationForm is 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.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.