Custom Signup Form with Extra Fields

A snippet demonstrating how to customize the signup form with additional fields.


# forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class CustomUserCreationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')
  

# views.py

from django.shortcuts import render, redirect
from .forms import CustomUserCreationForm

def register_view(request):
    form = CustomUserCreationForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('login')
    return render(request, 'register.html', {'form': form})
  

# templates/register.html

<h2>Sign Up</h2>
<form method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Register</button>
</form>
  
Explanation:
  • We create a custom form by subclassing UserCreationForm and adding an email field.
  • The Meta class tells Django which fields to show and which model to save.
  • In the view, we handle form validation and save the user on success.
  • You can extend this form further with fields like full name, phone number, or profile image.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.