为什么在使用 DJANGO formset 时无法从 CharField 中获取标签

Why do I not get labels rendered from CharField when using DJANGO formset

我有一个包含 2 个 CharField 的表单。两者都有标签="xyz"。 如果我在表单集中使用此表单,标签不会显示在 HTML

我试过查看渲染后的 HTML,但标签不见了。我只尝试了一种形式,而且有效。

表格:

class WindingVoltsSpecifier(forms.Form):
    winding_name = forms.CharField(max_length=20, label="Winding name")
    voltages = forms.CharField(max_length=20, label="Voltages")

查看:

def add_mains_transformer_primary_configs(request):
    # Add a new config

    # Create the formset, specifying the form and formset we want to use.
    # From https://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html
    VoltsSpecifierFormSet = formset_factory(WindingVoltsSpecifier)

    if request.method == 'POST':
        pass

    else:


        mt_config_form = MainsTransformerConfiguration()
        volts_formset = VoltsSpecifierFormSet()

        context = {
            'mt_config_form' : mt_config_form,
            'volts_formset' : volts_formset,

        }

    return render(request, 'designer/mains_configs.html', context)

模板:

{% extends 'designer/base.html' %}

{% load crispy_forms_tags %}

{% block title %}configuration{% endblock %}

{% block content %}
{% load static %}

<h1>Configuration</h1>

<form method="post">
    {% csrf_token %}


    {{ mt_config_form|crispy }}

    {{ volts_formset.management_form|crispy }}

    {% for volts_form in volts_formset %}

        <table>
        {% for form in volts_form %}
        {{ form }}
        {% endfor %}
    <table>
    <!--<div class="volts-formset">
        {{ volts_form.winding_name }}
        {{ volts_form.voltages }}
    </div>
    -->
    {% endfor %}

    {% if volts_formset.non_form_errors %}
        {% for error in volts_formset.non_form_errors %}
            {{ error|escape }}
        {% endfor %}
    {% endif %}




    <input type="submit" value="Update Profile" class="button" />
</form>

<script>
    $('.volts-formset').formset({
        addText: 'add winding',
        deleteText: 'remove'
    });
</script>



{% endblock %}

我希望标签在字段旁边。

标签不与字段一起呈现,您将不得不做一个 {{ FIELD.label_tag }}

它将是这样的:

<table>
    {% for field in volts_form %}
        {{ field.label_tag }}
        {{ field }}
    {% endfor %}
<table>

更多信息:Looping over the forms fields - Django documentation

希望这个解决方案有效!

{% for field in volts_forms %}
    {{ field.name}} <!-- label name -->
    {{ field }}<!-- ex. input -->
{% endfor %}