Django:将模板值发布到视图 [英] Django: posting a template value to a view
问题描述
我想发布到视图并使用隐藏的值字段和提交按钮来传递模板中的值。提交按钮中的值(即csrf_token)通过,但隐藏值未通过。我已经从Wezkrug调试器检查到 request.POST
仅包含表单值,而不包含我的'id'
值
I'm tying to post to a view and pass on a value from the template by using a hidden value field and a submit button. The values from the submit button (ie the csrf_token) gets through but the hidden value does not. I've checked from the Wezkrug debugger that request.POST
only contains form values and not my 'id'
value from the hidden field.
该按钮会将您带到一个表单,您可以在其中输入注释。我试图包括用户正在评论的 review.id
,以使评论变得容易。我的值是测试,不是出于测试目的。
The button takes you to a form where you can enter a comment. I'm trying to include the review.id
that the user is commenting on to make commenting easy. I have the value as 'test' not for test purposes.
我的表单:
<div>
<form method='POST' action='/add_comment/'>
{% csrf_token %}
<input type="hidden" name='id' value='test'>
<input type="submit" value="Make a Comment">
</form>
</div>
评论视图:
@login_required
def make_comment(request):
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.user = request.user
comment.save()
# render?
return HttpResponseRedirect('/results/', {
'restaurant': get_object_or_404(
Restaurant,
name=request.POST['name'],
address=request.POST['address']
)
})
else:
form = CommentForm()
return render(request, 'stamped/comment.html', {'form': form})
评论模型:
class Comment(models.Model):
content = models.TextField()
review = models.ForeignKey(Review)
user = models.ForeignKey(User)
date_added = models.DateTimeField(auto_now_add=True)
注释ModelForm代码:
Comment ModelForm Code:
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ('user', 'review',)
我一直在尝试遵循此问题中的策略,但是使用了request.session dict是不可取的,因为无论是否对其进行评论,都必须为每个评论存储一个ID。
I've been trying to follow the tactics in this question, but using the request.session dict is undesirable because Id have to store an id for every review regardless if they're are ever commented on.
What is a more efficient way to pass variables from Template to View in Django?
关于如何在POST中包括隐藏值的任何想法?谢谢!
Any ideas on how to include the hidden value in the POST? Thanks!
推荐答案
views.py
def make_comment(request):
if request.method == 'POST':
if 'prepair_comment' in request.POST:
review = get_object_or_404(Review, pk=request.POST.get('id'))
form = CommentForm({'review': review.id})
return render(request, 'stamped/comment.html', {
'form': form,
})
else: # save the comment
models.py
models.py
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ('user',)
widgets = {'review': forms.HiddenInput()}
restaurant.html
restaurant.html
<form method='POST' action='/add_comment/'>
{% csrf_token %}
<input type='hidden' value='{{ r.id }}' name='id'>
<input type="submit" name='prepair_comment' value="Make a Comment">
</form>
这篇关于Django:将模板值发布到视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!