Django中,在URL模式名称参数

问题描述 投票:41回答:1

我下面的教程在我的URL模式是:

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应该是基于类的观点。我想不出名字参数的含义。它是传递给视图一个默认的参数?

python django django-class-based-views urlconf url-pattern
1个回答
53
投票

不,它就是这样的Django给您命名的情况下,你的观点,你需要从你的代码,或者你的模板参考的选项。因为你避免硬编码在你的代码或里面你的模板网址,这是非常有用和良好做法。即使更改实际的URL,你不必到别的任何改变,因为你会参考他们的名字。

有观点e.x:

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)

更多here

e.x.模板

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

更多here

© www.soinside.com 2019 - 2024. All rights reserved.