15

模板中有多个复选框,如果渲染中包含值,则默认情况下将选中该选项。它适用于 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/

4

1 回答 1

21

正如@L_S 的评论。我用 调试dir(form),这里包含的所有值都是form.project.data正确的代码:

{% for choice in form.project %}
<labelc for="{{ choice.id_for_label }}">
    <input type="checkbox" name="{{ choice.data.name }}" id="{{ choice.id_for_label }}" 
    value="{{ choice.data.value }}"{% if choice.data.selected %} checked{% endif %}>
    {{ choice.data.label }}
</label>
{% endfor %}
于 2017-04-29T03:50:43.307 回答