我正在编写控件视图函数edit_article
,以更新模型表title
的{{1}}和content
的字段:
要更新标题和内容,我雇用了Article
article=form.save
在提交问题时报告错误
def edit_article(request, pk):
article = Article.objects.get(pk=pk)
if request.method == "POST":
form = ArticleForm(data=request.POST)
print(request.POST)
if form.is_valid():
article = form.save()
我没有更改django.db.utils.IntegrityError: (1048, "Column 'owner_id' cannot be null")
,只是将其保留为以前的状态。
通过显式重新分配属性来解决该问题:
owner_id
模型 if form.is_valid():
# article = form.save()
article.title = form.cleaned_data['title']
article.content = form.cleaned_data['content']
article.save()
Article
为什么class Article(models.Model):
STATUS = (
(1, 'normal'),
(0, '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)
class Meta:
ordering = ("id",)
def __str__(self):
return self.title
作为快捷方式失败了?
答案 0 :(得分:2)
如果要更新现有记录,则应将该模型的实例对象传递给表单。
因此您的代码将更改为
if request.method == "POST":
form = ArticleForm(instance=article, data=request.POST)
...