难以将外键值字段分配给循环内的表单

问题描述 投票:0回答:1

我在将外键值分配给循环内的表单字段时遇到问题。

我有一个 Django 应用程序,用户可以在其中提交问题的答案,每个答案可以有多个与之关联的评论。为了允许用户向每个答案添加评论,我在循环中实现了一个表单。但是,当用户使用表单提交评论时,它不是创建

CommentAForm
对象,而是创建
CommentQForm
对象。尽管尝试将答案 ID 作为
CommentAForm
中的隐藏字段传递,但该值似乎并未正确分配给
CommentAForm
。因此,评论没有与正确的表单或模型对象关联,我不知道发生了什么,我该如何修复它

浏览次数:

def view_question(request, slug):
    question = get_object_or_404(Question, slug=slug)
    answers = Answer.objects.filter(post=question)
    answers_comment = CommentA.objects.filter(post__id__in=answers)

     # this is the comment form for each question
    if request.method == 'POST':
        comment_form = CommentQForm(request.POST)
        if comment_form.is_valid():
            my_comment_form = comment_form.save(commit=False)
            my_comment_form.user = request.user
            my_comment_form.post = question
            my_comment_form.save()
            return redirect('View_Question', slug=slug)
    else:
        comment_form = CommentQForm()

    # This is the comment form each answer
    if request.method == 'POST':
        answer_comment_form = CommentAForm()
        if answer_comment_form.is_valid():
            my_answer_comment_form = answer_comment_form.save(commit=False)
            my_answer_comment_form.user = request.user
            my_answer_comment.post = Answer.objects.get(id=request.POST.get('answer'))
            my_answer_comment.save()
            return redirect('View_Question', slug=slug)
    else:
        answer_comment_form = CommentAForm()

    context = {"question":question, "answers":answers, "answer_form":answer_form,
    "comment_form":comment_form, "comments":comments, "answers_comment":answers_comment,
    "answer_comment_form":answer_comment_form}
    return render(request, 'view_question.html', context)

模板:

{% for answer in answers %}
    <div class="row my-3 border-top pb-2 mb-2 p-2">
        <div class="answer-icons">
            <span><i class="fas fa-arrow-up"></i>
                {{ answer.up_vote }}
            </span>
            <span><i class="fas fa-arrow-down"></i>
                {{ answer.down_vote }}
            </span>
        </div>
        <div class="answer-text card-content">
            <p>{{ answer.your_answer|convert_markdown|safe }}</p>
        </div>
    </div>

    <div class="comment-container m-3">
        {% for comment in answer.comments.all %}
            <div class="row border-bottom pb-2 mb-2">
                {{ comment.comment|convert_markdown|safe }}                
                <div class="comment-avatar">
                {% with comment.user.account as account %}
                    <a style="text-decoration: none;" class="user-avatar" href="{% url 'Public-Profile' slug=account.slug %}">
                        <span style="background-color: #888888; color: white;
                        border-radius: 5px; margin-right: 5px;">
                            -{{ comment.user.username }}
                        </span>
                    </a>
                    {{ comment.created_at|naturaltime }}
                {% endwith %}
                </div>
            </div>
        {% endfor %}
    </div>
    <div class="add-comment">
        <a href="" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
            <small>Add Comment</small>
        </a>
        <div class="collapse" id="collapseExample">
            <div class="row">
                <div class="col">
                    {% load crispy_forms_tags %}
                    <form action="" method="post">
                        {% csrf_token %}
                        {{ answer_comment_form|crispy }}
                        <input type="hidden" name="answer" value="{{ answer.id }}">
                        <button type="submit" class="btn btn-primary">submit</button>
                    </form>
                </div>
            </div>
          </div>
         </div>
{% endfor %}

我的模特:

class CommentA(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    comment = models.TextField()
    post = models.ForeignKey(Answer, on_delete=models.CASCADE, related_name='comments')
    created_at = models.DateTimeField(auto_now_add=True)

class CommentQ(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    comment = models.TextField()
    post = models.ForeignKey(Question, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

表格:

class CommentAForm(forms.ModelForm):
    class Meta:
        model = CommentA
        fields = ['comment']
        widgets = {
            'comment': forms.Textarea(attrs={'rows':3, 'cols':15})
        }

class CommentQForm(forms.ModelForm):
    class Meta:
        model = CommentQ
        fields = ['comment']
        widgets = {
            'comment': forms.Textarea(attrs={'rows':3, 'cols':15})
        }
python django django-forms
1个回答
0
投票

该视图有 2 个 if 语句,都是

if request.method == 'POST':
,因此每次您尝试发布时,只需点击第一个,创建 CommentQObject,然后返回。

您需要为其他 POST 创建第二个端点/路由,或添加一些额外条件以确保您可以区分请求

© www.soinside.com 2019 - 2024. All rights reserved.