Django Register User
Creating new user accounts in your application
📝 What is User Registration?
User registration creates new accounts in your application. Django provides tools to build secure registration forms with validation, password hashing, and automatic user creation in the database.
# views.py - Simple registration
from django.contrib.auth.models import User
user = User.objects.create_user(
username='newuser',
email='[email protected]',
password='securepass123'
)
Registration Components
Registration Form
Collect user information
Validation
Check data quality
Password Security
Secure password handling
User Creation
Save to database
🔹 Creating a Registration Form
Build a registration form with username, email, and password fields. Include password confirmation to prevent typos and ensure users remember their passwords.
# forms.py
from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
class RegistrationForm(forms.Form):
username = forms.CharField(
max_length=150,
widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Choose a username'
})
)
email = forms.EmailField(
widget=forms.EmailInput(attrs={
'class': 'form-control',
'placeholder': '[email protected]'
})
)
password1 = forms.CharField(
label='Password',
widget=forms.PasswordInput(attrs={
'class': 'form-control',
'placeholder': 'Enter password'
})
)
password2 = forms.CharField(
label='Confirm Password',
widget=forms.PasswordInput(attrs={
'class': 'form-control',
'placeholder': 'Confirm password'
})
)
def clean_username(self):
username = self.cleaned_data.get('username')
if User.objects.filter(username=username).exists():
raise ValidationError('Username already taken')
return username
def clean_email(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email=email).exists():
raise ValidationError('Email already registered')
return email
def clean(self):
cleaned_data = super().clean()
password1 = cleaned_data.get('password1')
password2 = cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise ValidationError('Passwords do not match')
return cleaned_data
🔹 Registration View
Create a view that processes registration forms and creates new users. Handle validation errors gracefully and automatically log in users after successful registration.
# views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate
from django.contrib import messages
from .forms import RegistrationForm
def register_view(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
# Get cleaned data
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password1']
# Create user
user = User.objects.create_user(
username=username,
email=email,
password=password
)
# Optional: Add additional user info
user.first_name = request.POST.get('first_name', '')
user.last_name = request.POST.get('last_name', '')
user.save()
# Log the user in
login(request, user)
messages.success(request, f'Welcome {username}! Your account has been created.')
return redirect('dashboard')
else:
form = RegistrationForm()
return render(request, 'register.html', {'form': form})
🔹 Registration Template
Design a user-friendly registration page with clear labels and helpful error messages. Provide visual feedback for validation errors and successful submissions.
<!-- register.html -->
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<style>
.register-container {
max-width: 500px;
margin: 50px auto;
padding: 30px;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #333;
}
input {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
}
button {
width: 100%;
padding: 12px;
background: #28a745;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
}
button:hover {
background: #218838;
}
.error {
color: red;
font-size: 12px;
margin-top: 5px;
}
</style>
</head>
<body>
<div class="register-container">
<h2>Create Account</h2>
<form method="post">
{% csrf_token %}
<div class="form-group">
{{ form.username.label_tag }}
{{ form.username }}
{% if form.username.errors %}
<div class="error">{{ form.username.errors }}</div>
{% endif %}
</div>
<div class="form-group">
{{ form.email.label_tag }}
{{ form.email }}
{% if form.email.errors %}
<div class="error">{{ form.email.errors }}</div>
{% endif %}
</div>
<div class="form-group">
{{ form.password1.label_tag }}
{{ form.password1 }}
{% if form.password1.errors %}
<div class="error">{{ form.password1.errors }}</div>
{% endif %}
</div>
<div class="form-group">
{{ form.password2.label_tag }}
{{ form.password2 }}
{% if form.password2.errors %}
<div class="error">{{ form.password2.errors }}</div>
{% endif %}
</div>
{% if form.non_field_errors %}
<div class="error">{{ form.non_field_errors }}</div>
{% endif %}
<button type="submit">Register</button>
</form>
<p style="margin-top: 20px; text-align: center;">
Already have an account? <a href="{% url 'login' %}">Login here</a>
</p>
</div>
</body>
</html>
Output:
Create Account
Already have an account? Login here
🔹 Using Django's UserCreationForm
Django provides a built-in UserCreationForm that handles common registration needs. Extend it to add custom fields like email or additional user information.
# 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)
first_name = forms.CharField(max_length=30, required=False)
last_name = forms.CharField(max_length=30, required=False)
class Meta:
model = User
fields = ('username', 'email', 'first_name',
'last_name', 'password1', 'password2')
def save(self, commit=True):
user = super().save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
if commit:
user.save()
return user
# views.py
from .forms import CustomUserCreationForm
def register_view(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('dashboard')
else:
form = CustomUserCreationForm()
return render(request, 'register.html', {'form': form})
🔹 Email Verification
Add email verification to confirm user email addresses. Send verification links and activate accounts only after users click the confirmation link.
# views.py
from django.core.mail import send_mail
from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import render_to_string
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes
def register_view(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
# Create inactive user
user = form.save(commit=False)
user.is_active = False
user.save()
# Send verification email
current_site = get_current_site(request)
subject = 'Activate Your Account'
message = render_to_string('activation_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
})
send_mail(subject, message, '[email protected]', [user.email])
messages.success(request, 'Please check your email to activate your account')
return redirect('login')
else:
form = RegistrationForm()
return render(request, 'register.html', {'form': form})
🔹 URL Configuration
Set up URL patterns for registration pages. Include paths for registration, email verification, and success pages.
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('register/', views.register_view, name='register'),
path('login/', views.login_view, name='login'),
path('dashboard/', views.dashboard, name='dashboard'),
]