Why don't labels appear in my Django ModelForm?

I have a very simple ModelForm in my application that looks like this:

 # ModelForm class ProductForm(ModelForm): class Meta: model = MyModel exclude = ['created', 'last_modified', 'serial_number'] # Model class BaseModel(models.Model): created = models.DateTimeField(auto_now_add=True, blank=True, null=True) last_modified = models.DateTimeField(auto_now=True, blank=True, null=True) class MyModel(BaseModel): product = models.TextField(verbose_name='Product Name') serial_number = models.TextField(verbose_name='Serial Number') 

And a form that looks like this:

 # Form <form method="POST" action="{% url some_url %}"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {% for field in form %} {% if field.errors %} <div>{{ field.errors }}</div> {% endif %} <div> {{ field.label_tag }}: {{ field }} </div> {% endfor %} {% endfor %} <div class="actions"> <input class="button submit focus" type="submit" value="{% trans "Save" %}" /> </div> </form> 

When I look at a view using this, I just see a colon ( : followed by a text box: the label is gone.

According to the documentation for ModelForm :

In addition, each generated form field has attributes set as follows:

  • ...

  • The sign of the form fields is set in the verbose_name field for the model field, the first character being uppercase.

What mistake did I make?

I am using Django 1.4.1 if that matters.

+4
source share
2 answers

The only solution I managed to find that still allowed me to separate each line of the form was as follows:

 <form method="POST" action="{% url some_url %}"> {% csrf_token %} {{ formset.as_ul }} <div class="actions"> <input class="button submit focus" type="submit" value="{% trans "Save" %}" /> </div> </form> 

... the key element is {{ formset.as_ul }} instead of repeating through each field.

As for why the other solution listed (or the solution in the documentation) does not work, I will remain puzzled.

0
source

You must place the field label inside the <label> . So:

 <div> <label for="id_{{field.html_name}}">{{field.label}}:</label> {{ field }} </div> 
0
source

Source: https://habr.com/ru/post/1487941/


All Articles