"此字段需要错误",尽管它未在模型数据表中定义



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

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其外键是文章

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)

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

在您看来,它说CommentForm.

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

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

最新更新