views:

196

answers:

1

hi,

I've got the Category model and SearchForm form shown below. I'd like to do 2 things in my template:

-to separate in the form the Category instances having a given type to be able to apply a specific style to them in my CSS

-to show the hierarchy of my category instances

Basically I need to access the Category's parent and style in my template or to modify the rendering of my form. How can I do this? thanks Jul

Category model

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

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) 
A: 

Why is parent a ManyToManyField? Can a category have more than one parent?

The following should display category and its descendants and highlight categories of the type special:

In 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>
Dmitry Risenberg
Yes, a category can have several parents. Is there any way to modify the way the form is rendered?
jul
I don't think so, but do you really need category list as a part of form? You can render it separately and enclose all in <form> tag.And if a category can have multiple parents, do you want it to be displayed multiple times? If yes, just call render_category for each top-level category. If no, you probably should define a custom tag for that.
Dmitry Risenberg