Explanation: Create a form: This defines a form class based on a Django model. Handle form submission: If the form is valid, save the user instance. Authenticate the user using the provided credentials. If authentication is successful, log the user in. Render the form: Render the form template with the form instance as context..
# forms.py
from django import forms
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'email', 'password']
# views.py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from .forms import UserForm
def signup(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
form = UserForm()
return render(request, 'signup.html', {'form': form})