通过外键引用 Django contrib.admin 用户?
我正在开发一个小型 Django 网站,并使用 django.contrib.admin 来处理内容管理。我想捕获名字和名字文章首次保存时作者(管理员用户)的姓氏(如果其他用户编辑文章,则不会更新)。
IE。
class Article(models.Model)
title = models.CharField(max_length=50)
pub_date = models.DateTimeField('date published')
author = ForeignKey(???)
...
我需要写什么来获取该用户的名字和名字?创建新的 Article 对象时的姓氏字段?如果这些字段为空,我将默认使用他们的管理员用户名。
I'm developing a small Django site and I'm using django.contrib.admin to handle content management. I'd like to capture the first name & last name of the author (an Admin user) of an Article on its initial save (and not update it if another user edits the Article).
ie.
class Article(models.Model)
title = models.CharField(max_length=50)
pub_date = models.DateTimeField('date published')
author = ForeignKey(???)
...
What do I need to write to grab this user's first name & last name fields when creating a new Article object? I'd default to their admin username if those fields are blank.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
让您的模型使用 User 对象:
要防止此字段在更新时更改,请查看其他 SO 帖子:
Django admin:仅排除更改表单上的字段
要更改管理员的选择字段使用名字/姓氏,您可以尝试以下代码片段:
http://djangosnippets.org/snippets/1642/
更改管理员的视图,假设您是使用内置模板,您可以按照本文所述添加自定义列:如何在 django 管理界面中添加带有超链接的自定义列?
Have your model use the User object:
To prevent this field from being changeable on update, check out this other SO post:
Django admin: exclude field on change form only
To change the admin's Select field to use first/last name, you could try this snippet:
http://djangosnippets.org/snippets/1642/
To change the admin's view, assuming you are using the built-in templates, you could add a custom column as described on this post: How do I add a custom column with a hyperlink in the django admin interface?
我想你正在寻找这个:
I think you are looking for this:
看起来处理 get_full_name 的 None 或空白结果的最佳方法是用 models.ForeignKey(User) 填充 User.author ,然后在模板级别使用以下内容:
... via 这个答案。这允许我对用户的文章执行查询,但仍然可以优雅地处理空白的名字和名字。 last_name 字段(如果用户尚未输入),但也会在输入时动态更新)。
It looks like the best way to handle a None or blank result from get_full_name is to just populate User.author with models.ForeignKey(User) and then — at the template level — use the following:
... via this SO answer. This allows me to perform queries on a User's Articles, but still gracefully handles blank first_name & last_name fields if a User hasn't entered them yet, but will also update dynamically when they have).