Django:根据字段属性在模板中自定义表单

时间:2010-01-29 12:40:01

标签: django forms templates

我有以下所示的Category模型和SearchForm表单。我想在我的模板中做两件事:

- 以具有给定类型的Category实例的形式分隔,以便能够在我的CSS中将特定样式应用于它们

- 显示我的类别实例的层次结构

基本上我需要在模板中访问Category的父级和样式,或修改我的表单的呈现。 我怎样才能做到这一点? 谢谢 七月

类别模型

CATEGORY_TYPE = [
    (1, 'region'),
    (2, 'type'),
]

class Category(models.Model):

    parent = models.ManyToManyField('self', symmetrical=False, null=True, blank=True)
    type = models.PositiveSmallIntegerField(choices=CATEGORY_TYPE)

    class Translation(multilingual.Translation):
        name = models.CharField(max_length=100, unique=True)

    class Meta:
        verbose_name_plural = 'Categories'

    def __unicode__(self):
        return "%s" %(self.name)

SearchForm类

class SearchForm(forms.Form):

    query = forms.CharField(max_length=100, required=False)
    price_range = forms.IntegerField(widget=forms.Select(choices = PRICE_RANGES_AND_EMPTY), required=False)

    def __init__(self, *args, **kwargs):
        super(SearchForm, self).__init__(*args, **kwargs)
        self.fields['country'] = forms.ModelChoiceField(queryset=Country.objects.all().order_by('name'), empty_label='All', required=False)
        self.fields['category'] = forms.ModelMultipleChoiceField(queryset=Category.objects.all().order_by('name'),
widget=forms.CheckboxSelectMultiple(), required=False) 

1 个答案:

答案 0 :(得分:0)

为什么parentManyToManyField?一个类别可以有多个父级吗?

以下内容应显示category及其后代并突出显示类型special的类别:

在Python中:

class Level:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return str(self.value)

    def inc(self):
        return Level(self.value + 1)

render_to_response("render_category.html", { 'level' : Level(0), 'category' : category, 'special' : special })

render_category.html:

<div class = "category {% ifequal category.type special %}special{% endif %} level-{{ level }}">
    {% for child in category.category_set.all %}
        {% with child as category %}
            {% with level.inc as level %}
                {% include "render_category.html" %}
            {% endwith %}
        {% endwith %}
    {% endfor %}
</div>