从this question和接受的答案可以清楚地看出,使用上下文重定向的唯一方法是将其保存在会话中。为什么Django没有一个简单的redirect
方法需要像render
这样的上下文对象呢?为什么Django不允许使用上下文重定向
例如,让我们说,我有一个登录视图,接受GET
和POST
请求。 GET
请求只是呈现用户可以输入凭据的表单,这将触发对相同视图的POST
调用。
def login(request, *args, **kwargs):
if request.method == 'GET':
context = {}
context.update(csrf(request))
return render(request, 'login.html', context=context)
elif request.method == 'POST':
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('loggedin')
else:
# Redirect with a context object that has 'error':True,
# so that the login template can display error message:
# 'Username/password is incorrect'
redirect('login')
return redirect('invalid')
请注意,在用户名/密码错误组合的进入,我想将用户重定向到同一个登录页面与上下文中的错误变量如此设置,模板可以绘制出一个警告。
我知道,一个可能的答案是调用render
比redirect
定义上下文,但那么是不是是一个很好的做法,始终使用redirect
POST请求后?
谢谢。
您可以使用GET变量的重定向,也可以使用消息框架 –