django-model-utils StatusModel 可以提供人类可读的状态选项吗?
我正在尝试使用 Carl Meyer 的 StatusModel 功能 ="https://bitbucket.org/carljm/django-model-utils" rel="nofollow">django-model-utils 包来创建一个具有状态字段。这是一个非常好的设计,您可以从 StatusModel
继承模型,并将 Choices
对象传递给模型上名为 STATUS 的字段,该字段会自动创建“status”和“status_changed” ' 数据库表示中的字段。
我希望我的状态字段具有与其数据库表示形式不同的人类可读值,并且 Choices 类的文档说它可以传递一个双元组,其中第一个值是选择的数据库表示形式,第二个值是人类可读的值。但是,当我尝试使用上面的 Choices
对象对 StatusModel 执行此操作时,当我在模板中使用状态字段时,我仍然可以获得数据库表示形式。
这是我的模型类的摘录:
from django.utils.translation import ugettext as _
from model_utils import Choices
from model_utils.models import StatusModel
STATUS_CHOICES = Choices(
('awaiting_approval', _('Awaiting approval')),
('returned_to_submitter', _('Returned to submitter')),
('approved', _('Approved')),
('denied', _('Denied')),
)
class Petition(StatusModel):
STATUS = STATUS_CHOICES
...
这是我的模板:
<table>
<tr>
<th>Status</th>
</tr>
{% for petition in petitions %}
<tr>
<td>{{ petition.status }}</td>
<!-- expecting "Awaiting approval" but it displays "awaiting_approval" -->
</tr>
{% endfor %}
</table>
如何让模型类返回人类可读的状态?或者 StatusModel
不支持 Choices
对象的该功能吗?
I am trying to use the StatusModel feature of Carl Meyer's awesome django-model-utils package to create a model that has a status field. It's a very nice design in which you subclass your model from StatusModel
and pass a Choices
object to a field on the model called STATUS, which automatically creates 'status' and 'status_changed' fields on the database representation.
I would like for my status field to have a separate human-readable value than its database representation, and the documentation for the Choices
class says that it can be passed a two-tuple in which the first value is the database representation of the choice and the second is the human-readable value. But when I try doing this with my StatusModel using the above Choices
object, I still get the database representation when I use the status field in a template.
Here's an excerpt of my model class:
from django.utils.translation import ugettext as _
from model_utils import Choices
from model_utils.models import StatusModel
STATUS_CHOICES = Choices(
('awaiting_approval', _('Awaiting approval')),
('returned_to_submitter', _('Returned to submitter')),
('approved', _('Approved')),
('denied', _('Denied')),
)
class Petition(StatusModel):
STATUS = STATUS_CHOICES
...
and here's my template:
<table>
<tr>
<th>Status</th>
</tr>
{% for petition in petitions %}
<tr>
<td>{{ petition.status }}</td>
<!-- expecting "Awaiting approval" but it displays "awaiting_approval" -->
</tr>
{% endfor %}
</table>
How do I get the model class to return the human readable status? Or does StatusModel
not support that feature of the Choices
object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用普通的
get_FOO_display()
方法 - 在本例中{{ 请愿.get_status_display }}
You can just use the normal
get_FOO_display()
method - in this case{{ petition.get_status_display }}