- 用户注册:
- 使用
Django
内置的UserCreationForm
,可以快速实现用户注册表单。
- 创建一个视图函数来处理注册逻辑,示例代码如下:
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = UserCreationForm()
return render(request,'register.html', {'form': form})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Register</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
</body>
</html>
- 用户登录:
- 使用
Django
内置的AuthenticationForm
和login
函数。
- 视图函数如下:
from django.shortcuts import render, redirect
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login
def user_login(request):
if request.method == 'POST':
form = AuthenticationForm(data = request.POST)
if form.is_valid():
user = form.get_user()
login(request, user)
return redirect('home')
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form': form})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
</body>
</html>
- 用户认证:
Django
会在用户登录时自动进行认证。在需要认证的视图函数上,可以使用login_required
装饰器确保只有登录用户能访问,例如:
from django.contrib.auth.decorators import login_required
@login_required
def some_protected_view(request):
return render(request, 'protected.html')
- 用户角色与权限设置:
- 定义用户角色:可以通过
Django
的Group
来实现用户角色管理。首先导入Group
模型:
from django.contrib.auth.models import Group
- 分配用户到角色组:在用户注册或管理页面,将用户添加到相应的组,例如将用户设为作者:
author_group, created = Group.objects.get_or_create(name='author')
user.groups.add(author_group)
- 设置权限:
- 可以在
models.py
中为模型(如Article
)定义权限,例如:
from django.db import models
from django.contrib.auth.models import User, Group
class Article(models.Model):
title = models.CharField(max_length = 200)
content = models.TextField()
author = models.ForeignKey(User, on_delete = models.CASCADE)
class Meta:
permissions = [
("can_publish_article", "Can publish article"),
]
- 限制视图访问:在视图函数中检查用户是否有相应权限,例如:
from django.contrib.auth.decorators import user_passes_test
def is_author(user):
return user.groups.filter(name='author').exists() or user.is_superuser
@user_passes_test(is_author)
def publish_article(request):
# 发布文章的逻辑
pass
- 管理员默认拥有所有权限,因为
Django
的超级用户(管理员)有所有权限。对于普通权限控制,可以通过Group
和Permission
的关联来实现不同角色的不同权限。