47
I need to add user registration to my Django site. What is the best approach?
Loading...
Q&A · Answered
I need to add user registration to my Django site. What is the best approach?
Accepted answer
# forms.py
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
# views.py
from django.shortcuts import render, redirect
from django.contrib.auth import login
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'registration/signup.html', {'form': form})Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.