Django HttpResponseRedirect with int parameter

I want to pass an int ( user_id) parameter from an input view to another view. Is this possible within HttpResponseRedirect? I am trying something like this:

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

So far my urlconf:

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

But I do not know if this is correct. Any suggestions?

+5
source share
3 answers

Well, this is clearly not the case, because the URL you created does not match your URL.

The right way to do this is to rely on Django to do it for you. If you provide your URL definition:

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

then you can use django.core.urlresolvers.reverseto create this URL with your arguments:

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

, kwarg, args URL-, , .

+4

, , :

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

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

.

!

+3

It is possible, but it’s better to cancel the URL and then redirect to it:

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

You need to make sure your conf URL has a named parameter in it (in my example above it is a parameter with a name user_id.

+1
source

All Articles