[Answer]-Taking as a parameter but not using in view

1👍

You can use a non-capturing group:

url(r'^post/(?P<post_id>\d+)/(?:[\w|\W]+)/$', views.detail, name="detail"),   

0👍

In your detail view, you can either add the incoming slug parameter or just catch **kwargs as your last argument.

def detail(request, id, slug=''):
    # slug might be passed in, but you don't need to worry about it
    pass

You can’t just omit the slug parameter, as Django will pass it to the view, even though you don’t actually need it. This is because you have a capture group set up for it ((?P<slug>) in your pattern).

You might be able to just omit the capture group to prevent having the argument passed.

url(r'^post/(?P<post_id>\d+)/[\w|\W]+/$', views.detail, name="detail"),

Which should prevent it from being passed to your view. This is because you aren’t telling Django to capture it (No parentheses) and even further, you aren’t giving it a name (the ?P<name> part).


The other option is to use multiple url patterns, to capture the different possibilities (including the optional slug). This doesn’t appear to be what you are asking for, but it would handle the case where the slug was not actually passed into the view.

http://localhost:8000/post/5/

Though it’s up to you if you want to support that case.

Leave a comment