python – Django:将模板值发布到视图

问题:

我想发布到视图并使用隐藏值字段和提交按钮从模板传递值.提交按钮(即csrf_token)中的值通过,但隐藏值不通过.我从Wezkrug调试器检查过request.POST只包含表单值而不是隐藏字段中的’id’值.

背景:

该按钮将您带到可以输入注释的表单.我正在尝试包含用户评论的review.id,以便轻松进行评论.我有’测试’的价值不是为了测试目的.

我的表格:

<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代码:

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        exclude = ('user', 'review',)

我一直在尝试遵循这个问题中的策略,但是使用request.session dict是不可取的,因为Id必须为每次评论存储一个id,无论它们是否被评论过.

What is a more efficient way to pass variables from Template to View in Django?

关于如何在POST中包含隐藏值的任何想法?谢谢!

最佳答案 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

class CommentForm(ModelForm):
        class Meta:
               model = Comment
               exclude = ('user',)
               widgets = {'review': forms.HiddenInput()}

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>
点赞