Django模板关键字`choice_value`在1.11中不再起作用

时间:2017-04-28 07:57:45

标签: python django django-1.11

模板中有一个复选框,如果值包含在渲染中,默认情况下将选中该选项。它适用于1.10。

form.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 %}

views.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/

1 个答案:

答案 0 :(得分:14)

作为@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 %}