Reputation: 2078
I'm new to django (1.5.1) and got a bit stuk with HttpResponseRedirect. If I understand right that needs a static string, and when you want it to dynamic redirect, you get a reverse() or a get_absolute_url() I think I get the part of the get_absolute_url, but I'm stuck on redirecting to the following url (first is mysite.urls.py second is my characters.view.py
url(r'^users/', include('characters.urls')),
url(r'^(?P<user_id>\d+)/characters/$', views.user_characters, name='user_characters'),
from this view:
if new_char_form.is_valid():
#save form with commit=False
new_char_obj = new_char_form.save(commit=False)
#set user and save
new_char_obj.user = user
new_char_obj.save()
return HttpResponseRedirect('%s/characters/' % user.id)
So I know I can't use the HttpResponseRedirect that way, and since I can't include a get_absolute_url function in the user model, I found the next option.
Include this in my settings
ABSOLUTE_URL_OVERRIDES = {
'auth.users': lambda o: "/users/%s/" % o.id,
}
but then I have no clue how to call for that. Can someone please give me help (sort of stuck on this for some time)
With kind regards Hans
Upvotes: 2
Views: 1699
Reputation: 308839
The easiest way to redirect to the user_characters
view is to use the redirect
shortcut.
from django.shortcuts import redirect
# in the view
return redirect('user_characters', user.id)
This is equivalent to using HttpResponseRedirect
and reverse
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
# in the view
return HttpResponseRedirect(reverse('user_characters', args=[user.id]))
If you want to use ABSOLUTE_URL_OVERRIDES
to override the get_absolute_url
method for the User
model, you have to make sure that the url matches the format of your view named user_characters
.
ABSOLUTE_URL_OVERRIDES = {
'auth.users': lambda o: "/users/%s/characters/" % o.id,
}
You would then be able to call user.get_absolute_url()
in your views, and do
return HttpResponseRedirect(user.get_absolute_url())
Or, since the redirect
shortcut allows you to pass a model instance:
return redirect(user)
Upvotes: 5