感谢您对以下问题的帮助:
我需要在python应用程序中使用3个不同的模型,我希望用户从HTML表单填充 . 我想使用模型表单,并在一个字典中传递所有三种不同的表单(请参阅我的views.py):
def new_sales_trip(request):
if request.method == "POST":
Restaurant_Form = RestaurantForm(request.POST)
SalesEvent_Form = SalesEventForm(request.POST)
NextAction_Form = NextActionForm(request.POST)
if Restaurant_Form.is_valid() and SalesEvent_Form.is_valid() and NextAction_Form.is_valid():
Restaurants = Restaurant_Form.save()
SalesEvents = SalesEvent_Form.save(False)
NextActions = NextAction_Form.save(False)
SalesEvents.restaurants = Restaurants
SalesEvents.save()
NextActions.restaurants = Restaurants
NextActions.save()
return redirect('/')
else:
allforms = {
'Restaurant_Form': Restaurant_Form,
'SalesEvent_Form': SalesEvent_Form,
'NextAction_Form': NextAction_Form,
}
return render(request, 'sales/SalesTrip_form.html', allforms)
else:
Restaurant_Form = RestaurantForm()
SalesEvent_Form = SalesEventForm()
NextAction_Form = NextActionForm()
c = {}
c.update(csrf(request))
allforms = {
'Restaurant_Form': Restaurant_Form,
'SalesEvent_Form': SalesEvent_Form,
'NextAction_Form': NextAction_Form,
}
return render(request, 'sales/SalesTrip_form.html', allforms)
到目前为止它工作 - 但我不知道如何使用这个字典在我的模板中迭代槽,所以我不应该单独引用所有形式的名称 . 我尝试做这样的事情:
{% for key, value in allforms.items %}
{% for field in value %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10"> <!--this gonna be only displayed if there is an error in it-->
<span class="text-danger small">{{ field.errors }}</span>
</div>
<label class="control-label col-sm-2">{{ field.label_tag }}</label>
<div class="col-sm-10"> <!--this gonna be displayed if there is no error -->
{{ field }}
</div>
</div>
{% endfor %}
{% endfor %}
不幸的是,除了空白页面之外,它不会呈现任何内容 . 如果我尝试.items()属性比它说:
无法解析余数:来自'allforms.items()'的'()'
1 回答
您只需要将
()
添加到items
的末尾:例如 . ,
{%endfor%} {%endfor%}