1

因此,在我的 Django URLS 中,我希望能够支持:

mysite.com/section

mysite.com/section/

mysite.com/section/sectionAlphaNum

mysite.com/section/sectionAlphaNum/

我目前有作为 URL 模式:

(r'^section/(?P<id>\s?)?', section)

这应该使section/成为必需的以及可选之后的任何内容,但它似乎永远不会捕获我输入的任何 sectionAlphaNum。在我的views.py文件中,我有

def section(request,id):
    if id == '':
        # Do something with id
    else:
        # Do default action

但它似乎永远不会进入顶部 if 分支它用 id 做某事

4

4 回答 4

1

Can you try the following syntax: (r'^section/(?P<id>\w+)/$', section)?

于 2013-08-28T22:13:49.953 回答
1

In regular expressions the ^ and $ represent the start and end of the string respectively.

Hence the URL to display /section/ would be:

(r'^section/$', section_view)

while the URL to display a specific section /section/section-id/ would be :

(r'^section/(?P<section_id>\w+)$', section_detail_view)

Ideally you have separate views in your views.py:

def section_view(request):
    # show page about the various sections

def section_detail_view(request, section_id):
    # show page about specific section by section_id
于 2013-08-28T22:14:42.170 回答
1

urls.py:

...
(r'^section/$', section),
(r'^section/(?P<id>\w+)/$', section),
...

views.py:

def section(request, id=None):
    if id is None:
       ...
    else:
       ...

To append just slash (from /section to /section/) enable CommonMiddleware in Your settings' MIDDLEWARE_CLASSES.

于 2013-08-28T22:15:00.907 回答
0
(r'^section(?:/(?P<id>\w+))?/$', section)

注意最后一个?使整个(?:/(?P<id>\w+))可选。

其他答案缺少?或者他们没有/像我对第一个斜线 ( ) 所做的那样使其中一个斜线 ( ) 可选(?:/(...

r'^section/(?:(?P<id>\w+)/)?$'  # same result, last '/' optional.

并在函数中使参数可选:

def section(request, id=None):
    # ...
于 2013-08-28T22:43:38.990 回答