【问题标题】:django combining forms with elements from a list in a tabledjango 将表单与表中列表中的元素组合在一起
【发布时间】:2011-07-28 05:16:59
【问题描述】:

我有以下问题。我正在尝试创建一个像二维数组这样的表单,您可以在其中输入多个对象的多个特征的值。这导致在表格中显示单个对象的一组表单,其中单个表单水平显示。

我的模板现在看起来像这样:`

<table id="formset" class="form">
{% for form in formset.forms %}

    {% if forloop.first %}
        <thead><tr>
        <th></ th>
        {% for field in form.visible_fields %}
            <th>{{ field.label|capfirst }}</th>
            {% endfor %}
        </tr></thead>
    {% endif %}
    <tr class="{% cycle row1,row2 %}">

    <td>  {{ ?? }}  </ td>

    {% for field in form.visible_fields %}
        <td>
        {# Include the hidden fields in the form #}
        {% if forloop.first %}
            {% for hidden in form.hidden_fields %}
                {{ hidden.name }}
            {% endfor %}
        {% endif %}
        {{ field.errors.as_ul }}
        {{ field }}
        </td>
    {% endfor %}
    </tr>
{% endfor %}

`

这是从网上获取的代码顺便说一句。现在我想做的是以某种方式在表格前面放一列,只有一些文字说明对象的名称,但我似乎做不到。

我尝试从列表中添加它们,但问题是无法从列表中访问正确的元素。遍历列表会导致同样的问题。

我还尝试在表单中添加一个隐藏字段,在视图中设置该字段的值,然后尝试使用类似的方法来恢复它 form.my_field.value 但我似乎无法真正从该字段中获取值。我确实设法获得了该字段的名称,但该值是不可能的。

我可以想象使用一些 javascript 来执行此操作,但这确实是最后的手段。在我看来,像这样基本的东西必须有一个好的服务器端解决方案。

有什么想法吗?

【问题讨论】:

    标签: django django-templates django-forms


    【解决方案1】:

    如果您使用的是 Django 1.3,则可以渲染 raw value of a form field。假设您要呈现名为name 的字段的值:

    {{ form.name.value }}
    

    【讨论】:

    • 谢谢,我还在 1.2.3 中,这可能是它不起作用的原因。干杯。
    【解决方案2】:

    我想可能有几个解决方案,一种是使用现有的字段属性,如 namedescription - 然后数据将与字段本身绑定。

    您可以将自定义属性添加到表单字段并在代码中引用它们。

    或者使用自定义模板标签,当字段名作为参数传递时,它会返回一个文本:

    NAMES = {
        'field1': u'my description1',
        'field2': u'smthg else'
    }
    
    @register.simple_tag
    def get_text(name):
        return NAMES.get(name, u'--no description--')
    

    【讨论】:

      猜你喜欢
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 2018-04-15
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      相关资源
      最近更新 更多