EmailField placeholder in django form?

Hi everyone,

My first post, fingers crossed :). Just started learning django and need a help with setting “placeholder” value for the django form in email field. I figured how to remove “label”, but when I render the page label is gone as expected but placeholder is not there. Any suggestion is greatly appreciated!!

–models.py
class TestModel(models.Model):
email = models.EmailField()

–forms.py
class TestForm(forms.ModelForm):
class Meta:
model = TestModel
fields = [‘email’]
labels = {
‘email’: ‘’
}
widgets = {
‘test’: forms.EmailField(widget=forms.EmailInput(attrs={‘placeholder’: ‘Email to’}))
}

Cheers,
Gordon

See the docs on Overriding the default fields for the format of the widgets entry in the Meta class.

2 Likes

Thank you for the quick response Ken. Unfortunately, I was not able to figure how to put a placeholder from the documentation provided above. I don’t think anything is wrong with my syntax as I am getting no error message. It’s just that placeholder is not shown.

1 Like

Look at the example in the referenced documentation.

widgets is a dict where the key is the field name and the value is the widget to be used.

That’s not how you have your widgets dict defined.

This is how I understand that form should look as per documentation. I get no errors, the page loads fine but the email field has no placeholder value. What I am doing wrong here?

class TestForm(forms.ModelForm):

class Meta:
    model = TestModel
    fields = ['email']
    labels = {
        'email': '',
    }

    widgets = {
        'test': forms.EmailInput(attrs={'placeholder': 'email'})
    }
1 Like

OMG, it was typo in my widget. I used ‘email’ as field name yet ‘test’ in widget. As soon as I corrected it is working fine. It’s weird that PyCharm got me no error messages when saved the forms.py despite me referencing field that’s not defined.

Thank you Ken!!

That’s one of those items that makes sense once you understand what’s actually going on here.
The widgets dict isn’t referencing a field, it’s a place to define what widgets get used for fields. If that definition isn’t used by a form then it’s just not-used. (Notice that the key is a string and not a field.)

And, strictly speaking, this is not an error. It may not be what you wanted in this specific case, but there’s nothing fundamentally wrong with it and there are contexts where it would be right!

<opinion>I don’t rely upon editors to catch errors in Django. Yes, they’ll catch some, but there are so many aspects of Django that are “declarative” rather than “procedural” (very informal terms) that an editor can’t catch them.</opinion>