以下是一个简单的用户注册和登录功能的实现示例:
首先,在Django项目的models.py
中定义一个用户模型:
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
pass
然后,在settings.py
中配置Django使用这个自定义用户模型:
# settings.py
AUTH_USER_MODEL = 'your_app_name.CustomUser'
接下来,在views.py
中创建注册和登录的视图函数:
from django.shortcuts import render, redirect
from django.contrib import auth, messages
from .forms import CustomUserCreationForm, LoginForm
def register(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, '注册成功!')
return redirect('login')
else:
form = CustomUserCreationForm()
return render(request, 'register.html', {'form': form})
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = auth.authenticate(request, username=username, password=password)
if user is not None:
auth.login(request, user)
messages.success(request, '登录成功!')
return redirect('home')
else:
messages.error(request, '用户名或密码不正确。')
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})
def logout(request):
auth.logout(request)
messages.success(request, '已安全退出。')
return redirect('login')
在forms.py
中定义表单:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate
from django.contrib.auth.models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = CustomUser
fields = ("username",)
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
def authenticate(self, request):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
user = authenticate(request, username=username, pas