0

why this code not working, i get variable "data" from views.py

when i change data.numrooms with number like '1', it's working well, but is use data.numrooms that's not working

<select class="form-control" name="numadults">
      <option value=''>No. of Adult</option>
          {% for i in range %}
             {% if data.numadults == i %}
                <option value="{{ i }}" selected>{{ i }}</option>
             {% else %}
                <option value="{{ i }}">{{ i }}</option>
             {% endif %}
          {% endfor %}
</select>
2
  • 1
    Where do You use data.numrooms? I see only data.numadults. Commented Apr 10, 2019 at 10:52
  • what is range? and show us data Commented Apr 10, 2019 at 10:52

2 Answers 2

1

Why not put that logic in the view and pass it to template like this:

# view

adult_range = list(map(lambda x: (x, True) if x == data.numadults else (x, False), range(1,10))

# Template
  <option value=''>No. of Adult</option>
      {% for i, selected in adult_range %}
         {% if selected %}
            <option value="{{ i }}" selected>{{ i }}</option>
         {% else %}
            <option value="{{ i }}">{{ i }}</option>
         {% endif %}
      {% endfor %}
Sign up to request clarification or add additional context in comments.

Comments

1

Similarly to ruddra's solution, the easiest way to achieve this is probably to do the bulk of the logic in the view:

adults = [(element, element.number == data.numadults) for element in adult_list]

This will give you a list of two-tuples of (<adult object>, <boolean>) where the boolean represents the conditional you're trying to use in the template to decide whether to use selected attribute.

In the template, you can then base your conditional solely on that boolean:

<option value=''>No. of Adult</option>
{% for i, selected in adult_range %}
    {% if selected %}
        <option value="{{ i }}" selected>{{ i }}</option>
    {% else %}
        <option value="{{ i }}">{{ i }}</option>
    {% endif %}
{% endfor %}

Note though that you can also evaluate the condition inline, in the html tag, like so:

<option value="{{ i }}" {% if selected %} selected {% endif %}>

This might make for more readable code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.