gpt4 book ai didi

python - 如何使用反向正确执行 HttpResponseRedirect?

转载 作者:太空狗 更新时间:2023-10-30 00:21:42 24 4
gpt4 key购买 nike

当我尝试反转时,出现错误“* 之后的_reverse_with_prefix() 参数必须是一个序列,而不是整数”。我之前在 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)),
)

最佳答案

检查reverse()里面的args=(p.id),一定是args=(p.id,)。第一种形式被视为整数而不是序列。

引用文献 the docthe 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).

此外,使用 'reserve.views.view_reviews' 而不仅仅是 'view_reviews',因此:

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

检查 the doc of reverse

关于python - 如何使用反向正确执行 HttpResponseRedirect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11183704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com