简体   繁体   中英

How do I remove Label text in Django generated form?

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.

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 }}

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 = ""

If you're wanting to remove all labels, you can use:

class sign_up_form(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for key, field in self.fields.items():
            field.label = ""

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM