Home > Mobile >  django form doesn't display labels
django form doesn't display labels

Time:02-11

I'm new in django. I try to create a simple form based on the model. Imputs are displayed fine but i have problem with the labels.They don't appears on the page. I can't figure out where is my mistake. For my it should be working fine. Any idea what's is wrong here?

class RecForm (ModelForm):
    class Meta:
        model = Rec
        fields = ['name', 'kind',]
        labels = {
            'name': 'Here put your name',
        }

home.html

<form action="addrec" method="post">
    {% csrf_token %}
{% for i in form %}
 {{ i }}
    <br><br>
{% endfor %}
    
    <input type="submit" value="Submit">

{% endblock %}

CodePudding user response:

You're rendering the field in your template as {{ i }}, with i being an instance of a BoundField (code). BoundField.__str__ calls widget.render (code) and returns the output. widget.render renders the value of of the widget's template (see widget templates here https://github.com/django/django/tree/4.0.2/django/forms/templates/django/forms/widgets). None of these templates include the label tag.

To render the label tag your should call {{ i.label_tag }} (code), which will render the tag with all attributes Django knows about. Extra attributes may require adjustments.

  • Related