Django用户认证与权限管理:基于Django 3 by Example的完整实现
【免费下载链接】Django-3-by-ExampleDjango 3 by Example (3rd Edition) published by Packt项目地址: https://gitcode.com/gh_mirrors/dj/Django-3-by-Example
Django 3 by Example提供了全面的用户认证与权限管理解决方案,帮助开发者快速构建安全可靠的Web应用。本文将详细介绍如何利用Django内置功能和示例项目中的最佳实践,实现从用户注册、登录到细粒度权限控制的完整流程。
🚀 快速上手:Django认证系统基础
Django的认证系统位于django.contrib.auth模块,提供了开箱即用的用户管理功能。在Django 3 by Example的多个章节中都有应用,例如:
- 用户模型:通过
from django.contrib.auth.models import User导入内置用户模型 - 登录视图:在
Chapter10/educa/educa/urls.py中配置:path('accounts/login/', auth_views.LoginView.as_view(), name='login'), path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'), - 权限控制:使用
PermissionRequiredMixin实现基于类的视图权限控制
🔐 用户注册与个人资料管理
自定义用户注册功能
Django 3 by Example在Chapter04/bookmarks/account/forms.py中实现了完整的用户注册表单:
class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'first_name', 'email')对应的视图实现位于Chapter04/bookmarks/account/views.py:
def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Create a new user object but avoid saving it yet new_user = user_form.save(commit=False) # Set the chosen password new_user.set_password(user_form.cleaned_data['password']) # Save the User object new_user.save() # Create the user profile Profile.objects.create(user=new_user) return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form})个人资料扩展
为了存储用户额外信息,示例项目创建了Profile模型(Chapter04/bookmarks/account/models.py):
class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) def __str__(self): return f'{self.user.username} profile'🔑 登录认证与会话管理
基于类的登录视图
Django提供了LoginView和LogoutView等基于类的视图,在Chapter11/educa/educa/urls.py中配置:
path('accounts/login/', auth_views.LoginView.as_view(), name='login'), path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'),登录保护装饰器
使用@login_required装饰器保护需要认证的视图(Chapter06/bookmarks/images/views.py):
@login_required def image_create(request): # 视图逻辑... pass📊 权限控制高级应用
基于角色的访问控制
Django 3 by Example展示了如何使用PermissionRequiredMixin实现基于类的视图权限控制(Chapter12/educa/courses/views.py):
class CourseCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView): model = Course fields = ['title', 'slug', 'overview'] permission_required = 'courses.add_course' def form_valid(self, form): form.instance.owner = self.request.user return super().form_valid(form)API权限控制
在REST API中,可以自定义权限类(Chapter12/educa/courses/api/permissions.py):
from rest_framework.permissions import BasePermission class IsEnrolled(BasePermission): def has_object_permission(self, request, view, obj): return obj.students.filter(id=request.user.id).exists()💡 实用技巧与最佳实践
密码验证:Django设置中包含密码验证器(
Chapter04/bookmarks/bookmarks/settings.py):'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',用户注册表单:使用
UserCreationForm简化注册流程(Chapter11/educa/students/views.py):from django.contrib.auth.forms import UserCreationForm class StudentRegistrationView(CreateView): template_name = 'students/registration.html' form_class = UserCreationForm查询用户:通过User模型查询用户数据(
Chapter06/bookmarks/account/views.py):users = User.objects.filter(is_active=True)
通过Django 3 by Example提供的这些实现,开发者可以轻松构建安全、灵活的用户认证与权限管理系统,满足不同应用场景的需求。无论是简单的博客系统还是复杂的教育平台,这些最佳实践都能帮助你构建专业的用户管理功能。
要开始使用这些功能,你可以克隆项目仓库:
git clone https://gitcode.com/gh_mirrors/dj/Django-3-by-Example探索各个章节中的实现细节,特别是Chapter04到Chapter06以及Chapter10到Chapter14的相关代码,了解如何将这些功能集成到你自己的Django项目中。
【免费下载链接】Django-3-by-ExampleDjango 3 by Example (3rd Edition) published by Packt项目地址: https://gitcode.com/gh_mirrors/dj/Django-3-by-Example
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考