Django中的reverse()是什么? [英] what is reverse() in Django

查看:335
本文介绍了Django中的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?

如果有人给了答案,一些例子...

It would nice if someone gave an answer with some examples...

推荐答案

https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse

你的 urls.py 定义这个:

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

到这个网址:

<!-- 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)

p>

you could just do

return HttpResponseRedirect('/foo/')

但如果您以后要更改网址,您必须更新 urls.py 在你的代码中引用它。这违反了DRY(google it)。

but what if you want to change the url in future - you'd have to update your urls.py and all references to it in your code. This violates DRY (google it).

而是你可以说

from django.core.urlresolvers import reverse
return HttpResponseRedirect(reverse('url_name'))

这将查看项目中定义的所有URL,名称为 url_name ,并返回实际的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 - 如果要更改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. This whole idea of editing one place only is refered to as "Don't Repeat Yourself" and is something to strive for.

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

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