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.
精彩评论