2013-02-08 36 views
0

我有CharField使用model_utils.Choices模型:与model_utils.Choices自定义模板

from model_utils import Choices 

class UserTestStatistics(models.Model): 
TEST_STATUSES = Choices(
    ('NR', 'not_readed'),('NP', 'not_passed'), 
    ('FL', 'failed'), ('PD', 'passed'),   
) 
status = models.CharField(choices=TEST_STATUSES, max_length=2) 

在模板我想这取决于状态字段值添加自定义CSS类。我试过这个:

{% if lecture.status == 'NP' %} 
    label-warning 
{% endif %} 

这没有工作。然后我试过这个:

context['statuses'] = UserTestStatistics.TEST_STATUSES 

{% elif lecture.status == statuses.not_passed %} 
    label-warning 
{% endif %} 

它也失败了。这里是为什么:

>>> s = UserTestStatistics.objects.get(lecture=l) 
>>> type(s.status) 
<type 'unicode'> 
>>> type(UserTestStatistics.TEST_STATUSES.passed) 
<type 'str'> 

快速和肮脏的解决办法是添加自定义模板标签,将转换既没有代码,然后比较,但对我来说,它看起来像我错了somwhere。

任何人都可以请建议更漂亮的东西?

+0

我曾预料你尝试过的第一件事。 “{{lecture.status}}”的输出是什么? –

+0

你忘了Unicode的模型中的 – catherine

+0

有趣的事情:我一直在想这几天,却发现那里我错在两分钟后,我发表的问题。 Unicode方法与问题没有什么共同之处,它只是不同的模式。感谢大家。 – Melevir

回答

1

我宁愿采用具有属性的方法,而不是在模板上使用硬编码字符串。

@property 
def is_not_readed(self): 
    return self.status == UserTestStatistics.TEST_STATUSES.STATUS.NR 

所以,在你的模板:

​​

另外,您可以有TEST_STATUSES作为

Choices('draft', 'published') 
class UserTestStatistics(models.Model): 
    TEST_STATUSES = Choices('not_readed', 'not_passed', 'failed', 'passed') 
... 

所以,在模板:

{% if lecture.status = lecture.TEST_STATUSES.not_readed %} 
    label-warning 
{% endif %} 

记住,有魔术'弦'超过模范就重构和易读性而言,吃饭并不是那么好的想法。

我希望这可以帮助一些人。 或者如果您有不同的想法/方法,请让所有人都知道。

0
def __unicode__(self): 
    return self.status