模板中有多个复选框,如果渲染中包含值,则默认情况下将选中该选项。它适用于 1.10。
表格.py:
class NewForm(forms.Form):
project = forms.ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple,
queryset=Project.objects.filter(enable=True)
)
模板:
{% for p in form.project %}
<label for="{{ p.id_for_label }}">
<input type="checkbox" name="{{ p.name }}" id="{{ p.id_for_label }}"
value="{{ p.choice_value }}"
{% if p.choice_value|add:"0" in form.project.initial %} checked{% endif %}>
<p>{{ p.choice_label }}</p>
</label>
{% endfor %}
视图.py:
def order_start(request, order_id):
if request.method == 'POST':
form = NewForm(request.POST)
if form.is_valid():
order.end_time = timezone.now()
order.save()
order.project = form.cleaned_data['project']
order.save()
return HttpResponsec(order.id)
else:
form = NewForm(initial={
'project': [p.pk for p in order.project.all()],
})
return render(request, 'orders/start.html', {'form': form, 'order': orderc})
当我升级到 Django 1.11 时,{{ p.name }}
什么{{ p.choice_value }}
都不返回。我知道 1.11 已经删除choice_value
了,但是如何解决这个问题呢?
1.10 https://docs.djangoproject.com/en/1.10/_modules/django/forms/widgets/
1.11 https://docs.djangoproject.com/en/1.11/_modules/django/forms/widgets/