我在 Django 中遇到 HttpResponseRedirect 问题。看来,无论我尝试什么参数,它要么抛出错误,要么在不更改 URL 的情况下进行重定向。我在自定义 login_user View 上使用它,并且我希望地址栏中的 URL 在重定向后更改。如果我使用重定向而不是 HttpResponseRedirect,它不会改变。无论哪种方式,我都可以让它提供正确的模板,但 URL 保持不变。作为 Django 的新手,如果有人可以向我解释如何执行此操作以及为什么我当前的代码不起作用,将会很有帮助。 我在 Stack Exchange 上看到了几个与我类似的问题,但答案没有帮助。
这是我的views.py的相关部分(请注意,由于复制和粘贴到此处,缩进变得很奇怪,这并不是错误的原因)。
from django.http import *
from django.contrib.auth import authenticate, login, logout
def login_user(request):
logout(request)
username = password = ''
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect('dashboard')
else:
state = "Your account is not active, please contact the app administrator."
else:
state = "Your username and/or password were incorrect."
state = "Please log in below..."
context = RequestContext(request, {
'state': state,
'username': username,
})
return render_to_response('bank/auth.html', {}, context)
仪表板是另一个 View 的名称,它在我的索引 View 的重定向中工作正常。我也尝试过对网址进行硬编码,但这也不起作用。有什么建议么??谢谢。
请您参考如下方法:
如果您使用 HttpResponseRedirect
,则必须提供 url,而不是 url 的名称。
您可以使用 reverse
获取 URL :
from django.core.urlresolvers import reverse
def my_view(request):
...
return HttpResponseRedirect(reverse('dashboard'))
或使用redirect
快捷方式。
from django.shortcuts import redirect
def my_view(request):
...
return redirect('dashboard')
如果使用上述任一方法都不起作用,则 View 中的其他位置可能存在错误。很难判断在哪里,因为缩进不正确。尝试添加一些日志记录或打印语句,看看您是否真的将重定向返回到您认为的位置。