【问题标题】:How to create Student in Django admin, if Student is a class, inherited from User and has required fields如何在 Django 管理员中创建 Student,如果 Student 是一个类,继承自 User 并且具有必填字段
【发布时间】:2015-01-08 22:50:21
【问题描述】:

我正在使用 Django,我有两个模型,学生和教师,从用户继承。他们每个人都有用户字段(登录名/密码/组等),但用户有一个 OneToOne 字段,Student_Group,您可以在其中为该学生选择组(不是 Django 组,而是大学中的组,例如 MZ103、MZ203、 MZ303...)。

它创建正确,但是,当我在管理页面中创建学生时,Django(像往常一样,对于所有用户)只询问用户名/密码。我输入它,然后它会保存所有数据,然后您可以更改一些内容 - 组、权限、student_group,所有您想要的。

普通用户没关系,所有字段都变为空白,您可以更改它们。但是对于 Student 模型,Django 尝试使用 Student_Group = null 来保存它,并显示“错误,外键不能为空”

那么,我如何让 django 填写所有字段,然后保存(不仅仅是用户名/密码)?或者我还能如何在类中创建 OneToOne 引用,从 User 继承?

【问题讨论】:

  • 如果你也在这里分享你的代码,回答会很有帮助。
  • 很遗憾我现在不能这样做,但我可以在今天晚上添加它

标签: django inheritance


【解决方案1】:

您可以在保存前使用commit=False 添加代码。所以对于学生的例子:

# Create a form instance with POST data.
>>> f = AuthorForm(request.POST)

# Create, but don't save the new author instance.
>>> new_author = f.save(commit=False)

# Modify the author in some way.
>>> new_author.some_field = 'some_value'

# Save the new instance.
>>> new_author.save()

【讨论】:

    猜你喜欢
    • 2020-04-21
    • 2011-06-02
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 2016-04-19
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多