Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse urls for Django class based view

I'm trying to do something like:

in urls.py:

...
url(r'^(?P<pk>\d+)/$', VideoDetailView.as_view(), name='video_detail', kwargs={'foo:''})
...

in views.py

..
HttpResponseRedirect(reverse('video_detail', kwargs={'pk': id, 'foo':'bar'}))
...

But this doesn't seem to work. I get a Reverse for 'video_detail' with arguments '()' and keyword arguments '{'pk': 13240L, 'foo': 'bar}' not found.

However this does work:

....
HttpResponseRedirect(reverse('video_detail', kwargs={'pk': id}))
...

ie. removing foo: bar from the reverse call. What's the correct way to do this and pass in extra arguments in the reverse url?

like image 958
9-bits Avatar asked Dec 21 '11 18:12

9-bits


People also ask

How do I redirect a class-based view in Django?

Django Redirects: A Super Simple Example Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which you then return from your view. Assuming this is the main urls.py of your Django project, the URL /redirect/ now redirects to /redirect-success/ .

What does the Django URLs reverse () function do?

the reverse function allows to retrieve url details from url's.py file through the name value provided there. This is the major use of reverse function in Django. The redirect variable is the variable here which will have the reversed value. So the reversed url value will be placed here.

How can I get previous URL in Django?

You can do that by using request. META['HTTP_REFERER'] , but it will exist if only your tab previous page was from your website, else there will be no HTTP_REFERER in META dict . So be careful and make sure that you are using . get() notation instead.

What does As_view () do in Django?

Its the main entry-point in request-response cycle in case of generic views. as_view is the function(class method) which will connect my MyView class with its url. Returns a callable view that takes a request and returns a response: You just can't use class-based views like you could in normal function-based views.


1 Answers

reverse is a function that creates URL.

Because You have specified only pk pattern in your URL patterns, you can only use pk as argument to reverse (it really would not make sense to add foo since the generated url would be exactly the same for any foo value). You can add foo to URL pattern or create multiple named urls, ie:

url(r'^(?P<pk>\d+)/$', VideoDetailView.as_view(), name='video_detail', kwargs={'foo':''})
url(r'^(?P<pk>\d+)/$', VideoDetailView.as_view(), name='video_detail2', kwargs={'foo':'bar'})

or

url(r'^(?P<pk>\d+)/(?P<foo>\w+)/$', VideoDetailView.as_view(), name='video_detail')
like image 112
bmihelac Avatar answered Sep 22 '22 18:09

bmihelac