Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在同一页面编辑关联数据的问题:《Django企业开发实战》2020年3月河北第6次印刷第123页 #42

Open
MaoningGuan opened this issue Jun 12, 2020 · 0 comments

Comments

@MaoningGuan
Copy link

MaoningGuan commented Jun 12, 2020

你按书上的代码敲完之后,重新运行程序,当你在分类编辑页添加新的文章,保存的时候会提示以下错误:
NOT NULL constraint failed: blog_post.owner_id*


这是因为post的owner字段还没有赋值,但是该字段声明的时候设置为Not Null。
解决办法:
在CategoryAdmin中添加以下函数代码:

def save_formset(self, request, form, formset, change):
""" 修改关联对象数据 """
instances = formset.save(commit=False)
for instance in instances:
    if not hasattr(instance, 'owner'):  # 防止误修改其他文章的作者
        instance.owner = request.user  # 给owner字段赋值
        instance.save()
formset.save_m2m()

在save_formset()函数中,可以修改关联对象post中的字段。


多说一句,在PostInline 要把你要编辑的Post字段要设置显示出来,

fields = (
    'title',
    'desc',
    'status',
    'content',
    'tag',
)

这里设置的就是你要在Category编辑页中显示Post要编辑的字段。
其中post的 'category'字段不需要设置,,它默认的值就是你当前编辑的分类。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant