什么是reverse()? [英] What is reverse()?

查看:55
本文介绍了什么是reverse()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我读Django代码时,会在某些模板中看到 reverse().我不太清楚这是什么,但是它与HttpResponseRedirect一起使用.应该如何以及何时使用此 reverse()?

When I read Django code sometimes, I see in some templates reverse(). I am not quite sure what this is but it is used together with HttpResponseRedirect. How and when is this reverse() supposed to be used?

推荐答案

reverse() |Django文档

reverse() | Django documentation

让我们假设您在 urls.py 中定义了以下内容:

Let's suppose that in your urls.py you have defined this:

url(r'^foo$', some_view, name='url_name'),

然后在模板中,您可以将该网址引用为:

In a template you can then refer to this url as:

<!-- django <= 1.4 -->
<a href="{% url url_name %}">link which calls some_view</a>

<!-- django >= 1.5 or with {% load url from future %} in your template -->
<a href="{% url 'url_name' %}">link which calls some_view</a>

这将呈现为:

<a href="/foo/">link which calls some_view</a>

现在说您想在 views.py 中执行类似的操作-例如您正在其他视图(不是 some_view )中处理其他URL(不是/foo/),并且想要将用户重定向到/foo/(通常是成功提交表单的情况).

Now say you want to do something similar in your views.py - e.g. you are handling some other URL (not /foo/) in some other view (not some_view) and you want to redirect the user to /foo/ (often the case on successful form submission).

您可以这样做:

return HttpResponseRedirect('/foo/')

但是,如果您以后想更改URL,该怎么办?您必须在代码中更新 urls.py 的所有引用.这违反了 DRY(不要重复自己)原则和整个编辑理念只在一个地方-这是要争取的东西.

But what if you want to change the URL in the future? You'd have to update your urls.py and all references to it in your code. This violates the DRY (Don't Repeat Yourself) principle and the whole idea of editing in one place only - which is something to strive for.

相反,您可以说:

from django.urls import reverse
return HttpResponseRedirect(reverse('url_name'))

这会在项目中定义的所有URL中查找以名称 url_name 定义的URL,并返回实际的URL /foo/.

This looks through all URLs defined in your project for the URL defined with the name url_name and returns the actual URL /foo/.

这意味着您只能通过URL的 name 属性来引用URL-如果要更改URL本身或URL所引用的视图,则只能通过编辑一个位置来完成此操作- urls.py .

This means that you refer to the URL only by its name attribute - if you want to change the URL itself or the view it refers to you can do this by editing one place only - urls.py.

这篇关于什么是reverse()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆