开发者

In Django urls. How can we make the link argument as optional .i.e. (\w+)

I want to make the arguments i pass through the urls as o开发者_Python百科ptional.

 url(r'^dashboard/forms/(\w+)|/create/$','dashboard_message_create'),
 url(r'^dashboard/forms/(\w+)/delete/$', 'delete'),

The problem with using "|" is that django cannot distinguish between the above 2 urls. I am new to django . So any pointers in this direction will be very useful. Thanks in advance


You can try associating both with the same view

url(r'^dashboard/forms/create/$','dashboard_message_create'),
url(r'^dashboard/forms/(\w+)/create/$','dashboard_message_create'),

Then, make sure dashboard_message_create works without the argument

def dashboard_message_create(request, name=None):
    # Body


You can do better, using full re-superpowers (well, almost super, no lookahead in urlpatterns...):

url(r'^dashboard/forms/((?P<name>\w+)/)?create/$','dashboard_message_create'),
url(r'^dashboard/forms/(?P<name>\w+)/delete/$', 'delete'),

Add named args to your view and ignore the unnamed ones:

def dashboard_message_create(request, name, *args, **kwargs):
    pass

The name arg will be None when the ((?P<name>\w+)/)? token matches the empty string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜