Django 和 urls.py:如何通过命名 url 进行 HttpResponseRedirect?
我正在编写一个基于会员的 Web 应用程序,我需要能够在登录后重定向页面。 我想在登录应用程序的views.py 文件中使用urls.py 脚本中的命名url,但我无法弄清楚该怎么做。 我所拥有的是这样的:
def login(request):
if request.session.has_key('user'):
if request.session['user'] is not None:
return HttpResponseRedirect('/path/to/page.html')
我想要完成的事情是这样的:
def login(request):
if request.session.has_key('user'):
if request.session['user'] is not None:
return HttpResponseRedirect url pageName
执行此操作时出现语法错误,有什么想法吗?
I'm writing a member-based web application, and I need to be able to redirect the page after login. I want to use the named url from my urls.py script in my views.py file for the login application, but I can't for the life of me figure out what to do. What I have is this:
def login(request):
if request.session.has_key('user'):
if request.session['user'] is not None:
return HttpResponseRedirect('/path/to/page.html')
What I want to accomplish is something like:
def login(request):
if request.session.has_key('user'):
if request.session['user'] is not None:
return HttpResponseRedirect url pageName
I get syntax errors when I execute this, any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
if 语句的更简洁编写方式是
if request.session.get('user')
。 has_key 现在已被弃用,并且 .get() 返回 None (默认情况下,可以通过传递第二个参数进行更改)。因此,将其与苏联的答复结合起来:
A more concise way to write that if statement would be
if request.session.get('user')
. has_key is deprecated nowadays, and .get() returns None (by default, changeable by passing a second parameter).So combining this with Soviut's reply:
您需要使用
reverse( )
utils 函数。其中
args
满足 url 正则表达式中的所有参数。 您还可以通过传递字典来提供命名参数。You need to use the
reverse()
utils function.Where
args
satisfies all the arguments in your url's regular expression. You can also supply named args by passing a dictionary.正确答案来自 Django 1.3 开始,其中重定向方法隐式执行反向调用,是:
The right answer from Django 1.3 onwards, where the redirect method implicitly does a reverse call, is:
另请参阅 https://docs.djangoproject。 com/en/dev/topics/http/urls/#reverse-resolution-of-urls
Also see https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls