How do I remove Label text in Django generated form?

21,459

Solution 1

In ModelForms there will be default labels so you have to over-ride where you don't need labels

you can define it like this

class sign_up_form(forms.ModelForm):
    email = forms.CharField(widget=forms.Textarea, label='')
    class Meta:
        model = Users
        fields =['email']

This method will not include labels for your form, other method depends on rendering in template. You can always avoid labels from form <label>MY LABEL</label> instead of {{ form.field.label }}

Solution 2

In __init__ method set your field label as empty.This will remove label text.

def __init__(self, *args, **kwargs):
        super(sign_up_form, self).__init__(*args, **kwargs)
        self.fields['email'].label = ""
Share:
21,459
Yax
Author by

Yax

Updated on July 05, 2022

Comments

  • Yax
    Yax almost 2 years

    I have a form that is displaying well only for the label text that I don't want and I have tried all I could to let it off my form but it won't just go...

    forms.py:

    class sign_up_form(forms.ModelForm):
        class Meta:
            model = Users
            fields =['email']
            widgets = {
                'email': forms.EmailInput(attrs={
                    'id': 'email',
                    'class': 'form-control input-lg emailAddress',
                    'name': 'email',
                    'placeholder': 'Enter a valid email'})}
    

    I have tried: views.py:

    from django.shortcuts import render
    from mysite.forms import sign_up_form
    
    def register(request):
        sign_up = sign_up_form(auto_id=False)
        context = {'sign_up_form': sign_up}
        return render(request, 'mysite/register.html', context)
    

    I need my widgets as defined above.

  • Tariq Ahmed
    Tariq Ahmed about 2 years
    It is giving empty space..