Error URL redirection
urls.py:
url(r'^book/(?P<booktitle>[\w\._-]+)/(?P<bookeditor>[\w\._-]+)/(?P<bookpages>[\w\._-]+)/(?P<bookid>[\d\._-]+)/$', 'book.views.book', name="book"),
views.py:
def book(request, booktitle, bookeditor, bookpages, bookid, template_name="book.html"):
book = get_object_or_404(book, pk=bookid)
if booktitle != book.book_title :
redirect_to = "/book/%s/%s/%s/%s/%i/" % ( booktitle, bookeditor, bookpages, bookid, )
return HttpResponseRedirect(redirect_to)
return render_to_response(template_name, { 'book': book, },)
.
So the urls of each book are like this:
example.com/book/the-bible/gesu-crist/938/12/
I want that开发者_StackOverflow社区 if there is an error in the url, then I get redirected to the real url by using book.id in the end of the url.
For example if I go to:
example.com/book/A-bible/gesu-crist/938/12/
then I will get redirected to:
example.com/book/the-bible/gesu-crist/938/12/
.
but if I go to wrong url I will get this error:
TypeError at /book/A-bible/gesu-crist/938/12/
%d format: a number is required, not unicode
.
If I use %s then I will get this error:
*The page isn't redirecting properly Firefox has detected that the server is redirecting the request for this address in a way that will never complete. * This problem can sometimes be caused by disabling or refusing to accept cookies.*
Why ? What I have to do ?
All arguments passed to a view are strings. Shove it through int()
before using it, or just use %s
instead.
Yeah, just replace the %i
in
redirect_to = "/book/%s/%s/%s/%s/%i/" % ( booktitle, bookeditor, bookpages, bookid, )
With %s
. Don't bother casting it to an integer.
精彩评论