我无法迭代模板

时间:2016-03-01 19:06:37

标签: django forms loops

我有一个包含所有表单的可变字典,我想在模板上迭代显示我在字典上的所有表单,而不像{{example_form}}那样对其进行硬编码 这是我的代码

{% extends 'prescription_menu.html' %}
{% load bootstrap3 %}
{% load crispy_forms_tags %}

{% block title %}Physicians{% endblock title %}

{% block container %}
{% csrf_token %}
<div class="row">
    <div class="col-md-offset-2 col-md-8">
        {% for form in forms %}
            {{form}}
        {% endfor %}

    </div>
</div>
{% endblock container %}

这是我的观点

def UpdatePhysician(request,id):

forms = {}
physician = get_object_or_404(Physician, id=id)
employee = get_object_or_404(Employee, id=physician.employee.id)
person = get_object_or_404(Person, id=employee.person.id)
try:
    address = get_object_or_404(Address, id=return_id(str(person.addresses.values('id'))))
    address_form = AddressForm(request.POST or None, instance=address)
    forms.update({'address_form': address_form})
except:
    address = None
email = get_object_or_404(Email, id=return_id(str(person.emails.values('id'))))
phone = get_object_or_404(PhoneNumber, id=return_id(str(person.phone_numbers.values('id'))))

person_form = PersonForm(request.POST or None, instance=person)
employee_form = EmployeeForm(request.POST or None, instance=employee)
physician_form = PhysicianForm(request.POST or None, instance=physician)
email_form = EmailForm(request.POST or None, instance=email)
phone_form = PhoneForm(request.POST or None, instance=phone)

forms.update({'person_form': person_form,
              'physician_form': physician_form,
              'employee_form': employee_form,
              'email_form': email_form,
              'phone_form': phone_form,
              })



return render(request, 'UpdatePhysician.html',forms)

它不会给我任何错误,它只是不显示任何内容,例如,当我输入{{person_form}}时,我会得到我想要的表单。

2 个答案:

答案 0 :(得分:0)

您需要将表单添加到列表中:

form_list = [person_form, physician_form, employee_form, email_form, phone_form]

并将此添加到您的上下文字典中,在这种情况下,您的forms字典是context字典:

forms.update({'forms': form_list})

然后在你的模板中:

{% for form in forms %}
    {{form}}
{% endfor %}

答案 1 :(得分:0)

您的forms变量是dict。因此,您必须遍历模板中的dicht:

{% for name, form in forms.items %}
   {{form}}
{%endfor%}

在视图中,您必须将最后一行更改为

return render(request, 'UpdatePhysician.html', {'forms': forms)