在 django 模板中显示引用用户 ID 的用户名
我希望这是一个简单的问题。由于某种原因,我还没有解决方案。
我有一个来自 django reversion 的对象集:version_list。该集合中的每个对象都附加有一个用户 ID。如何获取与用户 ID 对应的用户名?
为了更清楚起见,如果 version_list 中的每个对象都有名称、日期和用户 ID,我如何将 version_list 集与用户表连接起来以找出哪个用户 id 与哪个名称对应?这是在视图中完成的,还是在模板中完成的?
I expect this is an easy question. For some reason, I don't have a solution yet.
I have an object set from django reversion: version_list. Each object in the set has a user id attached to it. How do I grab the user names that correspond to the user ID's?
To try to be clearer, if each object in version_list has a name, date, and user id, how can I join the version_list set with the user table to figure out what user id goes with which name? This is done in the view, or the template?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为您正在寻找一个简单的模板标签。
你会这样使用:
I think you're looking for a simple template tag.
Which you would use like:
除非这是为了某种旧版兼容性,否则您确实应该更改架构以使用
ForeignKey(User)
。该列的数据应该是相同的,因此,如果您已经有很多不想在数据库中丢失的内容,只需将模型字段更新为,如果该字段是,您甚至不必更改表已调用
user_id
。至于获取用户名,这总是在模板级别完成,但这取决于您想要全名 (Casey Stark) 还是用户名 (caseywstark)。
使用
{{ user }}
显示用户名,使用{{ user.get_full_name }}
显示全名。第二种方法调用模板内 User 对象的 get_full_name 函数。请记住,您必须设置 user.first_name 和 user.last_name 才能使其不返回空字符串。Unless this is for some sort of legacy compatibility, you should really change your schema to use a
ForeignKey(User)
. The data should be the same for this column, so if you already have a lot of stuff you don't want to lose in your database just update the model field toand you won't even have to alter the table if the field is already called
user_id
.As for getting the user's name, this is always done at the template level but it depends on whether you want a full name (Casey Stark) or a username (caseywstark).
Use
{{ user }}
to display the username and{{ user.get_full_name }}
to display a full name. The second method calls the get_full_name function of the User object inside your template. Just keep in mind that you must set user.first_name and user.last_name in order for this to not return an empty string.版本对象是否有用户属性(即ForeignKey)或者它只是一个整数字段?如果它是用户外键,您应该能够说:
否则您将需要向版本对象添加一个函数/属性来查找相关用户,例如
然后在您的模板中:
Does the version object has a user property (i.e., ForeignKey) or is it just an integer field? If it's a user foreign key, you should be able to say:
Otherwise you're going to need to add a function/ property to your version objects that looks up the related user, like
And then in your template:
我得到了 博客。
如果您的 Entries 模型中有一个指向
User
的ForeignKey
,那就更好了。Models.py:
Views.py:
Template.html:
I got a reference of Blog.
It's better if you have a
ForeignKey
toUser
in your Entries model.Models.py:
Views.py:
Template.html: