开发者

Is it possible to make positional argument optional in URL in Django

I have this in URL file

(r'^new/(?P<object_class>\w+)/(?P<action>\w+)/(?P<object_id>\d+)/$', create_object)

NOw for URL like /new/book/edit/5 it is working fine

开发者_如何学编程

But if i do /new/book/create then it says nor URL matched.

Is it possible that third argumrent is optional so that i can use one URL rule for above cases


(r'^new/(?P<object_class>\w+)/(?P<action>\w+)/((?P<object_id>\d+)/)?$', create_object)

This should do it. (Notice I wrapped object_id and the / in a (..)? to make it optional)

Now object_id should be none in the view.


You can mark one of the arguments as optional with the regex char for 0 or 1 a question mark) Using your example I used:

(r'^new/(?P<object_class>\w+)/(?P<action>\w+)(/(?P<object_id>\d+))?/$', create_object)

The important thing to note is that a trailing / should still be present.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜