【问题标题】:Django form generated twiceDjango 表单生成了两次
【发布时间】:2016-04-14 18:30:36
【问题描述】:

我将我的简单 django 申请表包装在一些 css 中,并意识到我的表单被生成了两次(下图)

我希望它以表格的形式出现,您可以在下面的代码中看到我明确地将表格包装在表格中。然而,表格出现在表格上方,然后又出现在表格中。我重新检查了我的代码,但似乎无法弄清楚问题是什么

相关代码 - 生成表单的模板

<a href="/ad_accounts"> All Accounts </a>
<br />
<table class="table table-bordered table-striped">
    <form action="." method="POST">{% csrf_token %}
    <thead>
        <th>Attribute</th>
        <th>Value</th>
    </thead>
    <tr>
        <td>Title</td>
        <td>
            {{ form.title }}
        </td>
    </tr>
    <tr>
        <td>Objective</td>
        <td><select class="select2_single form-control" tabindex="-1">
            <option value={{ form.objective }}</option>
                </select></td>
    </tr>
    {{ form.as_p }}
    <tr>
        <td><input class="btn btn-success" type="submit" value="Submit"/></td>
    </tr>
    </form>

forms.py

from django import forms

class CampaignForm(forms.Form):
    """ Form for creating new Campaign """

    def __init__(self, *args, **kwargs):
        objectives = kwargs.get('objectives')
        if objectives:
            kwargs.pop('objectives')
        else:
            objectives = list()
        super(CampaignForm, self).__init__(*args, **kwargs)
        self.fields['title'] = forms.CharField(max_length=50)
        self.fields['objective'] = forms.ChoiceField(choices=objectives)

【问题讨论】:

    标签: python html django forms


    【解决方案1】:

    {{ form.as_p }}是django内置的渲染形式。您还手动渲染了相同的内容,因此可能没有必要这样做。

    请参阅 django 文档关于 render form in template

    【讨论】:

    • 天啊!感谢您的帮助
    猜你喜欢
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    相关资源
    最近更新 更多