Django, name parameter in urlpatterns

那年仲夏 提交于 2019-12-17 22:33:48

问题


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...,
)

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?


回答1:


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.

e.x with views:

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)

More here.

e.x. in templates

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

More here.



来源:https://stackoverflow.com/questions/12818377/django-name-parameter-in-urlpatterns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!