5

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?

1
  • I think you can use next argument of login view (docs). It will be the simpliest. Commented May 28, 2012 at 13:13

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Finally, I combined the above answers by doing:

url = reverse('profile', kwargs={ 'user_id': user.id })
return HttpResponseRedirect(url)

and

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

and it worked perfectly.

thank you!

Comments

1

That is possible but it's better to reverse the URL and then redirect to it:

url = reverse('name_of_url', kwargs={ 'user_id': user.id })
return HttpResponseRedirect(url)

You should make sure that your URL conf has a named parameter in it (in my above example it's a parameter called user_id.

Comments

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.