使用jinj在python中通过从视图传递到html的字典中的表单进行迭代

2024-05-14 15:40:15 发布

您现在位置:Python中文网/ 问答频道 /正文

如果您能帮助解决以下问题,我将不胜感激:

我需要在python应用程序中使用3种不同的模型,我希望用户从HTML表单填充。我想使用模型表单,并在一个字典中传递所有三种不同的表单(请参阅my 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()属性,它会说:

Could not parse the remainder: '()' from 'allforms.items()'


Tags: divformfieldifisrequestsavecol
1条回答
网友
1楼 · 发布于 2024-05-14 15:40:15

您只需将()添加到items的末尾:

例如

 {% 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%}

相关问题 更多 >

    热门问题