我有变量 CHOICES 和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')
如何将CHOICES添加到html标签?
我想将<option>IT</option>
替换为 CHOICES中的部门
完整代码
<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>
我尝试了
{% for department in CHOICES %}
<option value={{ department.0 }}>{{ department.1 }}</option>
{% endfor %}
但“选择”为空
答案 0 :(得分:1)
您需要类似的东西
{% for department in CHOICES %}
<option value={{ department.0 }}>{{ department.1 }}</option>
(% endfor %}
确保从您的视图中将CHOICES
作为上下文传递
答案 1 :(得分:1)
通常,您在Django表单中使用ChoiceField
或TypedChoiceField
,并且在模板中呈现表单时,<select>
结构在某种程度上是自动的。 / p>
但是对于极少数情况,您确实可以将其传递到模板,如Tushortz在他的答案中所示。
答案 2 :(得分:0)
正确的方法-
<div class="a">a</div>
<div class="b">b</div>
<div class="c">c</div>