Django:如何从用户ID获取用户全名

use*_*940 4 django django-models

型号:author = models.ForeignKey(User)

用户ID(例如174948)保存到列author_id.在模板中,我使用{{post.author}}显示用户ID我还想显示该特定用户的全名.如何在模板中执行此操作?

Ign*_*ams 7

通过使用它的方法.

{{post.author.get_full_name}}
Run Code Online (Sandbox Code Playgroud)


小智 7

这取决于用户对象是否设置了名字和/或姓氏字段。

如果不是(例如,刚刚创建了一个新用户),则调用{{ post.author.get_full_name }}可能会返回一个空字符串。

这种方法更可靠:

{{ post.author.get_full_name|default:post.author.username }}
Run Code Online (Sandbox Code Playgroud)