首页 > 解决方案 > 为什么即使数据有效,Django 也不接受来自表单的数据?Django-蟒蛇

问题描述

我正在使用 Django 中的模态和表单 我为我的帖子模态创建了一个评论模式 我使用外键将我的评论与帖子相关联,它可以通过手动将评论添加到我网页的管理部分的帖子中,但只要我尝试使用我的表单的前端表示来做同样的事情,以便用户可以向帖子添加评论,它不能按预期工作,我也无法自动将我的帖子与我的评论相关联,我一直在改变事情形成了 2 天,结果仍然一样。任何人都可以帮助我:{这就是我的模式的样子:

class Comment(models.Model):
    post = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments')
    author = models.CharField(max_length=200)
    text =  RichTextField()
    created_date = models.DateTimeField(auto_now_add= True)
    active = models.BooleanField(default=False)

表格:

    class CommentForm(forms.ModelForm):

    class Meta:
        model = models.Comment
        fields = ['author', 'text']





这是我在 Views.py 中的视图:


def article_detail(request, slug):
    article = Article.objects.get(slug = slug)

    articles = Article.objects.all()
    comment_form = CommentForm()



    post = get_object_or_404(Article, slug=slug)

    comments = post.comments.filter(active=True)


    if request.method == 'POST':
        form =  forms.CreateArticle(request.POST, request.FILES)
        if form.is_valid():
            # Create Comment object but don't save to database syet
            new_comment = form.save()
            # Assign the current post to the comment
            new_comment.post =  comment_form.instance.article_id
            # Save the comment to the database
            new_comment.save()
    else:
        comment_form = CommentForm()

    return render(request, 'articles/article_detail.html', {'article':article, 'articles':articles, 'comment_form': comment_form , })

表单前端表示为:


        <form method="post" style="margin-top: 1.3em;">

          {{ comment_form }}
          {% csrf_token %}
          <button type="submit" class="btn btn-outline-success">Submit</button>
        </form>


标签: pythonhtmldjangodjango-models

解决方案


您的正确代码应如下所示

def article_detail(request, slug):

    articles = Article.objects.all()
    comment_form = CommentForm()


    post = get_object_or_404(Article, slug=slug)

    comments = post.comments.filter(active=True)


    if request.method == 'POST':
        form =  CommentForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            # Create Comment object but don't save to database syet
            new_comment = form.save(commit=False)
            new_comment.post = post
            new_comment.save()
    else:
        comment_form = CommentForm()

    return render(request, 'articles/article_detail.html', {'article':post, 'articles':articles, 'comment_form': comment_form })

推荐阅读