[Fixed]-How can I hide a django label in a custom django form?

23πŸ‘

βœ…

I wouldn’t recommend removing the label as it makes the form inaccessible. You could add a custom CSS class to the field, and in your CSS make that class invisible.

EDIT

I missed that the input was hidden so accessibility isn’t a concern.

You can render the form fields directly in your template:

<form ...>
    {% for field in form.hidden_fields %}
        {{ field }}
    {% endfor %}

    {% for field in form.visible_fields %}
        {{ field.label }} {{ field }}
    {% endfor %}
</form>
πŸ‘€John Keyes

20πŸ‘

Now,(my django version is 2.1.4), you can solve in this way -> Edit forms.py file:

password = forms.CharField(label=False)
πŸ‘€ZDL-so

7πŸ‘

If you use the form.as_p or form.as_table method, Django shouldn’t display the labels for your hidden fields anyway, so there’s no need to change the label in your __init__ method.

{{ form.as_table }}

If you are customizing the form template, you can use the field.is_hidden attribute to check whether the field is hidden.

{% if field.is_hidden %}
   {# Don't render label #}
{% endif %}

Alternatively, you can loop over hidden and visible fields separately, and omit the label for hidden fields.

πŸ‘€Alasdair

4πŸ‘

i found this useful and it works for me!

class CustomForm(forms.Form):
class Meta:
    ...  #other properties such as model, fields, widgets and help text
    labels = {
       'comment' : '',
    }
πŸ‘€Asad Ali

3πŸ‘

You need to give False and it will work:

self.fields['mp_e'].label = False

django version: 2.2

πŸ‘€Pushya shah

1πŸ‘

Go to your forms.py file and
add label = false

as
below

name = forms.CharField(required=True, max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Enter Name *'}), label=False)
πŸ‘€ziyad akmal

0πŸ‘

Unless I’m misunderstanding your question, you just need to add the mp_e field to the exclude tuple under the meta class. is this not what you need?

class MPForm( forms.ModelForm ):
    def __init__( self, *args, **kwargs ):
        super(MPForm, self).__init__( *args, **kwargs )

    class Meta:
        model = MeasurementPoint
        exclude = ('mp_order','mp_e')  
πŸ‘€joeButler

Leave a comment