Django 可选的 url 参数 [英] Django optional url parameters
问题描述
我有一个像这样的 Django URL:
I have a Django URL like this:
url(
r'^project_config/(?P<product>w+)/(?P<project_id>w+)/$',
'tool.views.ProjectConfig',
name='project_config'
),
views.py:
def ProjectConfig(request, product, project_id=None, template_name='project.html'):
...
# do stuff
问题是我希望 project_id
参数是可选的.
The problem is that I want the project_id
parameter to be optional.
我希望 /project_config/
和 /project_config/12345abdce/
是同样有效的 URL 模式,以便 if project_id
已通过,然后我可以使用它.
I want /project_config/
and /project_config/12345abdce/
to be equally valid URL patterns, so that if project_id
is passed, then I can use it.
就目前而言,当我访问没有 project_id
参数的 URL 时,我得到 404.
As it stands at the moment, I get a 404 when I access the URL without the project_id
parameter.
推荐答案
有几种方法.
一种是在正则表达式中使用非捕获组:(?:/(?P
使正则表达式 Django URL 标记可选
One is to use a non-capturing group in the regex: (?:/(?P<title>[a-zA-Z]+)/)?
Making a Regex Django URL Token Optional
另一种更容易遵循的方法是拥有多个符合您需求的规则,所有规则都指向同一个视图.
Another, easier to follow way is to have multiple rules that matches your needs, all pointing to the same view.
urlpatterns = patterns('',
url(r'^project_config/$', views.foo),
url(r'^project_config/(?P<product>w+)/$', views.foo),
url(r'^project_config/(?P<product>w+)/(?P<project_id>w+)/$', views.foo),
)
请记住,在您的视图中,您还需要为可选的 URL 参数设置默认值,否则会出现错误:
Keep in mind that in your view you'll also need to set a default for the optional URL parameter, or you'll get an error:
def foo(request, optional_parameter=''):
# Your code goes here
这篇关于Django 可选的 url 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!