Django11—授权和验证_django 授权,百度Golang岗一面+二面内容
在Django中实现用户认证系统,你需要使用Django自带的auth
应用。以下是一些核心功能的示例代码:
- 用户注册:
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('some_view_name')
else:
form = UserCreationForm()
return render(request, 'signup.html', {'form': form})
- 用户登录:
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm
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('some_view_name')
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form': form})
- 用户登出:
from django.contrib.auth import logout
def user_logout(request):
logout(request)
return redirect('some_view_name')
- 检查当前用户是否认证:
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
# 这里的代码只会在用户登录后运行
...
这些代码片段展示了如何在Django中实现用户注册、登录和登出功能,并且使用了Django的内置装饰器来确保某些视图只有认证用户可以访问。
评论已关闭