Episode 19 of 32

User Creation Form

Use Django built-in UserCreationForm — render a registration form with username, password, and password confirmation fields.

User Creation Form

Django provides a built-in form for user registration called UserCreationForm. It handles username, password, password confirmation, and validation.

The Signup View

# accounts/views.py
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm

def signup_view(request):
    form = UserCreationForm()
    return render(request, 'accounts/signup.html', {
        'form': form
    })

The Signup Template

<!-- templates/accounts/signup.html -->
{% extends 'base_layout.html' %}

{% block content %}
    <h2>Sign Up</h2>
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Create Account</button>
    </form>
{% endblock %}

Key Parts

ElementPurpose
method="POST"Form data is sent securely in the request body
{% csrf_token %}Security token — prevents cross-site request forgery
{{ form.as_p }}Renders form fields wrapped in <p> tags

Form Rendering Options

{{ form.as_p }}     <!-- Each field in a <p> tag -->
{{ form.as_table }}  <!-- Each field in a <tr> tag -->
{{ form.as_ul }}     <!-- Each field in a <li> tag -->

Key Takeaways

  • UserCreationForm is built-in — no need to create your own registration form
  • Always include {% csrf_token %} in forms — it is required for security
  • {{ form.as_p }} renders all form fields as HTML automatically
  • The form is a GET request initially (display the blank form)