Python 如何使用选项(元组)在多个字段中显示全名?
我有这样一个简单的模型Python 如何使用选项(元组)在多个字段中显示全名?,python,django,django-admin,django-templates,django-orm,Python,Django,Django Admin,Django Templates,Django Orm,我有这样一个简单的模型 class UserType( models.Model ) : def __unicode__( self ) : return self.name TYPE_CHOICES = ( ( 'ad', 'administrator' ), ( 'mo', 'moderator' ), ( 'vi', 'viewer' ), ( 'pm'
class UserType( models.Model ) :
def __unicode__( self ) :
return self.name
TYPE_CHOICES = (
( 'ad', 'administrator' ),
( 'mo', 'moderator' ),
( 'vi', 'viewer' ),
( 'pm', 'property manager' ),
( 'po', 'property owner' ),
( 'vm', 'vendor manager' ),
( 've', 'vendor' ),
( 'te', 'tenant' ),
)
name = models.CharField( max_length = 2, choices = TYPE_CHOICES )
User type:
<ul>
{% if user_object.profile.user_types.all %}
{% for user_type in user_object.profile.user_types.all %}
<li>{{ user_type|capfirst }}</li>
{% endfor %}
{% else %}
<li>No user type</li>
{% endif %}
</ul>
在admins.py
中,我为UserProfile
设置了filter\u horizontal=('user\u types',)
,它的ManyToManyField
设置为UserType
。但是在UserProfile
admin页面中,M2M的水平过滤器仅显示元组的短名称:
同样在模板中,我想显示一个特定用户拥有的用户类型列表。我的模板代码如下所示
class UserType( models.Model ) :
def __unicode__( self ) :
return self.name
TYPE_CHOICES = (
( 'ad', 'administrator' ),
( 'mo', 'moderator' ),
( 'vi', 'viewer' ),
( 'pm', 'property manager' ),
( 'po', 'property owner' ),
( 'vm', 'vendor manager' ),
( 've', 'vendor' ),
( 'te', 'tenant' ),
)
name = models.CharField( max_length = 2, choices = TYPE_CHOICES )
User type:
<ul>
{% if user_object.profile.user_types.all %}
{% for user_type in user_object.profile.user_types.all %}
<li>{{ user_type|capfirst }}</li>
{% endfor %}
{% else %}
<li>No user type</li>
{% endif %}
</ul>
用户类型:
{%if user\u object.profile.user\u types.all%}
{user_object.profile.user_types.all%}
- {{user_type}capfirst}
{%endfor%}
{%else%}
- 没有用户类型
{%endif%}
在模板上,它只显示短名称。我知道通常我可以通过执行类似于{{get\u user\u type\u display}}
的操作来显示它的长名称,但是在M2M的情况下,它不起作用
所以我的问题有两个:
class UserType( models.Model ) :
TYPE_CHOICES = (
( 'ad', 'administrator' ),
( 'mo', 'moderator' ),
( 'vi', 'viewer' ),
( 'pm', 'property manager' ),
( 'po', 'property owner' ),
( 'vm', 'vendor manager' ),
( 've', 'vendor' ),
( 'te', 'tenant' ),
)
STR_CHOICES = { key : value for (key,value) in TYPE_CHOICES }
name = models.CharField( max_length = 2, choices = TYPE_CHOICES )
def __str__(self):
return self.STR_CHOICES[self.name]
阿斯特万诺维奇的回答对我很有帮助。我想补充一点 如果你在很多领域都有一个模型。。。 如果您已在模板中上载此区域的所有其他模型。。。 您将不再调用人类可读的名称
获取
选项\u显示
用名称
调用它就足够了,这是返回值
因此,现在只有在模板
{{usertype}}
中,模板代码的第5行中可能存在的副本将不起作用<代码>settings.py
中设置了TEMPLATE\u STRING\u如果无效
。我的第一个问题呢?我可能错了,但我想你可能想到了“TL;DR”,而只是读了我问题的最后一部分。我已经说过我知道关于get\u FOO\u display
。你是对的,因为你需要使用user\u type\u name\u display
FOO
是你想要显示的字段的名称。谢谢你的建议。我终于使用了用户类型。获取名称显示
:-)。关于管理页面有什么线索吗?哦,我必须在\uuuuuunicode\uuuuuuu
中设置它(你写了\uuuuuu str\uuuuuu
,但几乎是一样的东西)!谢谢!