我有一个表格可以查看产品。要查看产品,我创建了一个表单,但是当用户提交他的评论时,我希望他保持在同一页面上。
这是我的网址:
url(r'^(?P<slug>[^/]+)/$', 'reviews.views.single_product'),
这是我的表格
<form class = "form-inline" action = "/text/" method="post">{% csrf_token %}
<strong><h3>Revise este produto</h3></strong><br>
{% for field in form %}
<font size = "4">
{% if field.field.required %}
<div class="field-wrapper question-required">
{{ field.errors }}
<span class="asterix"> * </span><label class="label-inline">{{ field.label }}</label>
{% else %}
<div class="field-wrapper">
{{ field.errors }}
<label class="form-help-text">{{ field.label }}</label>
{% endif %}
<br />
<div class="">
{{ field }}
</div>
</div>
</li>
</font>
{% endfor %}
<br>
<button class="btn btn-primary" type="submit" name="submit" value = "Envia Review"><h4>Pronto!</h4></button>
</form>
这是呈现页面的视图:
def single_product(request, slug):
product = get_object_or_404(Product, slug=slug)
prod = Product.objects.get(slug=slug)
reviews = Review.objects.get(product=prod.id)
reviewmatrix = {}
i = 0
try:
for rev in reviews:
reviewmatrix[str(i)] = [[review.review_text]]
u = User.objects.get(username=rev.user)
i = i + 1
except:
u = User.objects.get(username=reviews.user)
reviewmatrix[str(i)] = [[reviews.review_text]]
if request.method=="POST":
form = responseForm(request.POST, review=review)
if form.is_valid():
response = form.save()
msg = 'Obrigado por avaliar ' + prod.name
return render(request, 'product_detail.html', {'prod':prod, 'reviews':reviews, 'user':u.first_name, 'msg':msg})
else:
form = ReviewForm()
args = {}
args.update(csrf(request))
return render(request, 'product_detail.html', {'prod':prod, 'reviews':reviews, 'user':u.first_name, 'form':form})
答案 0 :(得分:2)
处理完表单后,您可以对同一视图执行HttpResponseRedirect
。您应该能够从表单中的字段中识别出slug。
或者,您可以使用action = "."
将表单提交到同一视图,并且可以避免重定向到原始页面。