Django admin 用户ForeignKey 的默认值
author = models.ForeignKey(User)
有什么方法可以设置此字段的默认值以自动选择登录用户吗?我知道您可以在保存方法中执行此操作,但我的客户要求在编辑时自动默认为登录用户以避免混淆。
这篇文章介绍如何在保存过程中更新它,只需不在编辑时。
author = models.ForeignKey(User)
Is there any way I can set the default value of this field to automatically select the logged in user? I know you can do this in the save method but my client has requested that it automatically defaults to the logged in user at edit time to avoid confusion.
This article goes into how to update it during save, just not at edit time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您正在编辑的对象是新的,您可以覆盖模型的管理部分,以不显示作者,因为它应该设置为当前用户,并且只有当您正在编辑对象时,该字段才会显示?
您可以通过重写 ModelAdmin 的 get_form 方法来完成此操作。
You could override the Admin part of your model to not display the author if the object that you are editing is new because it should be set to the current user and only if you are editing an object does the field show?
You would do this by overriding the get_form method of ModelAdmin.