“此字段需要错误”,尽管它未在模型数据表

时间:2018-06-09 15:04:43

标签: django

我尝试使用模型数据创建一篇新文章:

class Article(models.Model):
    STATUS = (
        (0,  'normal'),
        (-1, 'deleted'),
    )
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    block = models.ForeignKey(Block, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    content = models.TextField() # set the widget
    status = models.IntegerField(choices=STATUS)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

但是,当我从浏览器提交数据时,系统会提示comment字段是必需的,因为它不是文章字段中的一个。

我在CBV print(form.errors.as_data())

中添加了测试命令class ArticleCreateView(View):
Starting development server at http://127.0.0.1:8001/
Quit the server with CONTROL-C.
{'comment': [ValidationError(['This field is required.'])]}
[09/Jun/2018 22:50:16] "POST /article/create/1 HTTP/1.1" 200 3694

我有其他表Comment,其ForeignKey是文章

class Comment(models.Model):
    STATUS = (
        (0,  'normal'),
        (-1, 'deleted'),
    )
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    comment = models.TextField() # set the widget
    status = models.IntegerField(choices=STATUS)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.comment

views.py

class ArticleCreateView(View):

    template_name = "article/article_create.html"

    def get(self, request, block_id):
        block = Block.objects.get(id=block_id)
        context = {'b':block}
        return render(request, self.template_name,context)

    def post(self, request, block_id):

        block = Block.objects.get(id=block_id)
        form = CommentForm(request.POST)

        if form.is_valid():
            article = form.save(commit=False)
            article.owner = request.user
            article.block = block
            article.status = 0
            article.save()
            return redirect(f"/article/list/{ block_id }")
        else:
            print(form.errors.as_data())
            context = {'b':block,
                        "form":form}
            return render(request, self.template_name, context)

我不知道为什么会抛出这样的错误?

1 个答案:

答案 0 :(得分:1)

在您看来,它显示CommentForm

class ArticleCreateView(View):
    def post(self, request, block_id):
        ...
        form = CommentForm(request.POST)

也许您想使用ArticleForm或代码中的任何内容?