6

I have a url defined as follows:

url(r'^details/(?P<id>\d+)$', DetailView.as_view(), name='detail_view'),

In my templates, I want to be able to get the following url: /details/ from the defined url.

I tried {% url detail_view %}, but I get an error since I am not specifying the id parameter.

I need the url without the ID because I will be appending it using JS.

How can I accomplish this?

3
  • 3
    What would the purpose be? This URL can't be matched if there is no id parameter, so why would you want to create a link to it? Maybe you're trying to solve another problem and your solution just isn't the right one? Commented Aug 29, 2012 at 18:40
  • I will append the ID using javascript, but I'd like to have the URL as js variable. Commented Aug 29, 2012 at 18:41
  • 2
    You could always use the reverse with id = -1 (which you wouldn't expect to be an ID anyway) and replace the rightmost -1 with the proper ID when you need it. Seems very hackish to me if you ask me, but always better than defining another URL. Commented Aug 29, 2012 at 19:07

1 Answer 1

6

Just add this line to your urls.py:

url(r'^details/$', DetailView.as_view(), name='detail_view'),

or:

url(r'^details/(?P<id>\d*)$', DetailView.as_view(), name='detail_view'),

(This is a cleaner solution - thanks to Thomas Orozco)

You'll need to specify that id is optional in your view function:

def view(request, id=None):
Sign up to request clarification or add additional context in comments.

4 Comments

Note: the two urlpatterns will need to have a unique name, so if you name this one "detail_view", rename your original to something like "detail_view_with_id".
If you're going to modify the view to accept an optional parameter, I think you might as well make the parameter optional: r'^details/(?P<id>\d*)$'.
how do you specify the id parameter in the template {% url detail_view %}
Not really a solution for Class Based views :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.