Django,urlpatterns中的名称参数 [英] Django, name parameter in urlpatterns

查看:182
本文介绍了Django,urlpatterns中的名称参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在跟踪其中的urlpatterns为以下内容的教程:

I'm following a tutorial where my urlpatterns are:

urlpatterns = patterns('',
    url(r'^passwords/$', PasswordListView.as_view(), name='passwords_api_root'),
    url(r'^passwords/(?P<id>[0-9]+)$', PasswordInstanceView.as_view(), name='passwords_api_instance'),
    ...other urls here...,
)

PasswordListView PasswordInstanceView 应该是基于类的视图。
我无法弄清楚 name 参数的含义。

The PasswordListView and PasswordInstanceView are supposed to be class based views. I could not figure out the meaning of the name parameter. Is it a default parameter passed to the view?

推荐答案

否。只是django使您可以选择命名视图,以防您需要从代码或模板中引用它们。这是有用且很好的做法,因为可以避免在代码或模板内部对URL进行硬编码。即使您更改了实际的url,也不必更改任何其他内容,因为您将按名称引用它们。

No. It is just that django gives you the option to name your views in case you need to refer to them from your code, or your templates. This is useful and good practice because you avoid hardcoding urls on your code or inside your templates. Even if you change the actual url, you don't have to change anything else, since you will refer to them by name.

例如,带有视图的

from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse #this is deprecated in django 2.0+
from django.urls import reverse #use this for django 2.0+

def myview(request):
    passwords_url = reverse('passwords_api_root')  # this returns the string `/passwords/`
    return HttpResponseRedirect(passwords_url)

更多此处

ex在模板中

<p>Please go <a href="{% url 'passwords_api_root' %}">here</a></p>

更多此处

这篇关于Django,urlpatterns中的名称参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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