Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly do HttpResponseRedirect with reverse?

Tags:

python

django

I am getting an error "_reverse_with_prefix() argument after * must be a sequence, not int" when I try to reverse. I previously hardcoded the parameter in the view but am trying to make it dynamic. Any advice?

View:

def add_review(request, product_id):
    p = get_object_or_404(Product, pk=product_id)
    if request.method == 'POST':
        form = ReviewForm(request.POST)
        if form.is_valid():
            form.save()
            #HARDCODED: return HttpResponseRedirect('/products/1/reviews/')
            return HttpResponseRedirect(reverse('view_reviews', args=(p.id)))
    else:
        form = ReviewForm()
    variables = RequestContext(request, {'form': form})
    return render_to_response('reserve/templates/create_review.html', variables)        


def view_reviews(request, product_id):
    product = get_object_or_404(Product, pk=product_id)
    reviews = Review.objects.filter(product_id=product_id)
    return render_to_response('reserve/templates/view_reviews.html', {'product':product, 'reviews':reviews},
    context_instance=RequestContext(request))


urlpatterns = patterns('reserve.views',
    url(r'^clubs/$', 'index'),
    url(r'^products/(?P<product_id>\d+)/reviews/$', 'view_reviews'),
    url(r'^products/(?P<product_id>\d+)/add_review/$', 'add_review'),
    url(r'^admin/', include(admin.site.urls)),
)
like image 275
sharataka Avatar asked Jun 25 '12 04:06

sharataka


2 Answers

Check args=(p.id) inside the reverse(), it must be args=(p.id,). The first form is treated as integer instead of a sequence.

Refs the doc and the tutorial:

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).

Also, use 'reserve.views.view_reviews' instead of merely 'view_reviews', thus:

reverse('reserve.views.view_reviews', args=(p.id,))

Check the doc of reverse

like image 79
okm Avatar answered Nov 04 '22 04:11

okm


Since your pattern assigns a match to a variable, it is considered a keyword argument, so you should adjust the call to reverse.

return HttpResponseRedirect(reverse('view_reviews', kwargs={'product_id':p.id})

like image 34
Burhan Khalid Avatar answered Nov 04 '22 05:11

Burhan Khalid