Question

I pass to the template dictionary

CHOICES_gender = (('0', 'М'), ('1', 'Ж'))

I need to put in the element 'select' keys and values ​​CHOICES_gender.

I try to do as follows:

<select class="fld_gender" id="fld_gender">
    {% for (key, item, ) in CHOICES_gender.values() %}
        <option name="key" value="volvo">item</option>
    {% endfor %}
</select>

but get the following error:

Exception Type: TemplateSyntaxError
Exception Value:    
Could not parse the remainder: '()' from 'CHOICES_gender.values()'
Was it helpful?

Solution

I think this will fix your problem :)

<select class="fld_gender" id="fld_gender">
{% for key, item in CHOICES_gender %}
      <option name="{{ key }}" value="volvo">{{ item }}</option>
{% endfor %} 
</select>

There is no need to call the function .values() on the tuple.

OTHER TIPS

The CHOICES_gender you provided is not a dict object

perhaps you omitted a step when converting it to be a dictionary?

CHOICES_gender = {'0':'М', '1':'Ж'}

and then the correct syntax is:

<select class="fld_gender" id="fld_gender">
    {% for key, item in CHOICES_gender.items %}
        <option name="key" value="volvo">item</option>
    {% endfor %}
</select>

You could convert your existing object to a dictionary:

CHOICES_dictionary = { o[0]:o[1] for o in CHOICES_gender }

If you want to keep the object as is:

CHOICES_gender = (('0', 'М'), ('1', 'Ж'))

You can unpack it similar to you would in a python:

<select class="fld_gender" id="fld_gender">
    {% for key, item in CHOICES_gender %}
        <option name="key" value="volvo">item</option>
    {% endfor %}
</select>

Your error was being thrown because you cannot call methods on objects in a django template with parentheses at the end which is why it complained about the () on the end.

ref: Django Book Ch 4, About a 1/3 of the way down the page in "Context Variable Lookup"

As a side note, you will never be able to call a method with arguments, in which case you can write a filters if you really feel the need, but generally all the data needs to be some what serialized, i.e. staticly laid out instead of generated in the template.

Typically you do any preparation of the data in the views.py and then give presentation logic in the template.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top