Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access queryset of a modelChoiceField in template tag

I have a model which has a color field

class EventCategory(models.Model):
    name = models.CharField(max_length = 10)
    color = models.CharField(max_length = 8)

and Event model

class Event(models.Model):
    #fields
    category = models.ForeignKey(EventCategory)

How can I access the modelChoice queryset in my template tag. Doing something like that doesn't work (suppose i have a form sent to my template)

<select name="category" id="id_category">
    {%for category in form.category.queryset%}
        <option value="{{category.pk}} style="background-color:{{category.color}};">category.name</option>
    {%endfor%}  
</select>

I know in my python files I can do something like this:

form = EventForm()
for c in form.fields['category'].queryset:
    print c

And will give me its EventCategory instance. But how can i do the same thing inside a template tag?

EDIT Got it!!!

{%for category in in form.category.field.queryset%}
    etc
{%endfor%}
like image 726
Apostolos Avatar asked Feb 04 '26 02:02

Apostolos


1 Answers

Got it!!!

{% for category in form.category.field.queryset.all %}
    etc
{% endfor %}

Though I deal with a new problem now maybe you know why it would be happening. If I add a new category it won't show on the Select box, not until I restart the server.

EDIT: It works normally when I use it as normally as {{form.category}}

EDIT2: Edited now it works as it should.

like image 118
Apostolos Avatar answered Feb 05 '26 18:02

Apostolos