Reputation: 457
I have variable CHOICES and ListView.
CHOICES = [
('ALL', 'ALL'),
('IT', 'IT'),
('FINANCE', 'FINANCE'),
('OTHER', 'OTHER'),
]
class HomePageView(ListView):
model = Vacancy
template_name = 'vacancy_list/vacancy_list.html'
paginate_by = 10
page_kwarg = 'vacancy'
context_object_name = 'vacancies'
queryset = Vacancy.objects.order_by('-published_date')
How can I add CHOICES to the html tag ?
I want to replace <option>IT</option>
to something like for department in CHOICES
full code
<div class="col-lg-3 col-md-4 col-xs-12">
<select name="q2" class="form-control" id="exampleFormControlSelect1">
{% if user.is_authenticated %}
<option>{{ user.department }}</option>
{% else %}
<option>ALL</option>
{% endif %}
<option>IT</option>
<option>Finance</option>
<option>Other</option>
</select>
</div>
I tried
{% for department in CHOICES %}
<option value={{ department.0 }}>{{ department.1 }}</option>
{% endfor %}
but CHOICES is empty
Upvotes: 1
Views: 563
Reputation: 5045
you need something like
{% for department in CHOICES %}
<option value={{ department.0 }}>{{ department.1 }}</option>
(% endfor %}
make sure CHOICES
is passed as a context from your view
Upvotes: 1
Reputation: 8202
Normally, you use a ChoiceField
or TypedChoiceField
in a Django form, and to a greater or lesser extent the <select>
structure is automagical when you render the form in your template.
But for edge cases you can indeed pass it to your template as Tushortz shows in his answer.
Upvotes: 1
Reputation: 782
Correct way -
{% for department in CHOICES %}
<option value="{{department[0]}}">{{ department[1] }}</option>
(% endfor %}
Upvotes: 0