Search code examples
pythondjangourldjango-urlsdjango-mptt

Advanced URLs in Django


The task is to write two url patterns.

The first one will take a single argument <path>, which can be any url with random depth:

test/dorogi/

or

test/foo/bar/as/deep/as/you/want

The second one will be the same as the first one, but with a number in the end.

test/dorogi/1/

It talkes two arguments: <path> and <pk>. The last one is a number.


I made a solution for the first pattern:

url(r'^(?P<path>.*)/', mptt_urls.view(model='activities.models.Category', view='activities.views.category',
                                         slug_field='slug'), name='activities'),

But how do I make the second one and prevent any conflicts beteween them?

It should be something like:

url(r'^...', views.ArticleDetailView.as_view(), name='article-detail'),

Solution

  • Just add the second parameter to the regex for the first pattern:

    r'^(?P<path>.*)/(?P<pk>\d+)/$'
    

    But make sure to put that before the first one in your list of URLs.

    (Note that you should definitely terminate your pattern with a $, as I did above.)