Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django return HttpResponseRedirect to an url with a parameter

I have a situation in my project where i need to make a redirection of the user to an url containing a parameter, it is declared in the urls.py like:

url(r'^notamember/(?P<classname>\w+)/$',                             notamember,                            name='notamember'),) 

How can i put that parameter in the return HttpResponseRedirect? I tried like:

return HttpResponseRedirect('/classroom/notamember/classname') 

anyway, this is foolish, i know, i cannot consider the classmane as a parameter. For clarity, my view.py is:

def leave_classroom(request,classname):     theclass = Classroom.objects.get(classname = classname)     u = Membership.objects.filter(classroom=theclass).get(member = request.user).delete()     return HttpResponseRedirect('/classroom/notamember/theclass/') 

How can i include the variable theclass in that url? Thanks a lot!

like image 272
dana Avatar asked Jun 29 '10 10:06

dana


2 Answers

This should not be complicated. The argument to HttpResponseRedirect is simply a string, so the normal rules for building up a string apply here. However, I don't think you want the theclass variable in there, as that is a ClassRoom object, not a string. You presumably want the classname instead. adamk has given you the right answer here.

However, having said that you can just use a string, what you should actually do is use the reverse function. This is because you might later decide to change the URL structure, and rather than having to look through your code finding each place you've hard-coded the URL string, you should rely on having defined them in one single place: your urls.py file. So you should do something like this:

from django.core.urlresolvers import reverse  url = reverse('notamember', kwargs={'classname': classname}) return HttpResponseRedirect(url) 
like image 63
Daniel Roseman Avatar answered Sep 21 '22 07:09

Daniel Roseman


Try this:

return HttpResponseRedirect('/classroom/notamember/%s/' % classname) 

EDIT:

This is surely better (Daniel Roseman's answer):

from django.core.urlresolvers import reverse  url = reverse('notamember', kwargs={'classname': classname}) return HttpResponseRedirect(url) 
like image 44
adamk Avatar answered Sep 24 '22 07:09

adamk