Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django HttpResponseRedirect with int parameter

I want to pass an int parameter (user_id) from a login view to another view. Is that possible within an HttpResponseRedirect? I try something like this:

return HttpResponseRedirect("/profile/?user_id=user.id")

While my urlconf is:

(r'^profile/(?P<user_id>\d+)/$', '...')

But I don't know if that's the right way. Any suggestions?

like image 867
marlen Avatar asked May 28 '12 13:05

marlen


1 Answers

Well, that's clearly not the right way, because the URL you create does not match the one in your urlconf.

The correct way to do this is to rely on Django to do it for you. If you give your URL definition a name:

urlpatterns += patterns('', 
    url(r'^profile/(?P\d+)/$', ' ...', name='profile'),
)

then you can use django.core.urlresolvers.reverse to generate that URL with your arguments:

redirect_url = reverse('profile', args=[user.id])
return HttpResponseRedirect(redirect_url)

Note it's better to use kwargs rather than args in your URLs, but I've kept it as you had originally.

like image 146
Daniel Roseman Avatar answered Sep 29 '22 00:09

Daniel Roseman