Adding an attribute to the <input> tag for a django ModelForm field

前端 未结 3 378
慢半拍i
慢半拍i 2021-02-02 10:32

I have a django model that I\'m displaying as a form using a ModelForm. The defaults work very well for me for the most part.

However, I would like my html

相关标签:
3条回答
  • 2021-02-02 11:07

    Slight change to @josh-smeaton 's answer.

    class AuthorForm(ModelForm):
    class Meta:
        model = Author
        widgets = {
            'name': forms.TextInput(attrs={'placeholder': 'name'}),
        }
    

    Without the "forms." in front of TextInput a NameError would be raised.

    Django Ver 2.0.1

    0 讨论(0)
  • 2021-02-02 11:14

    Personally I prefer to use this method:

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or 'email@address.nl'
    

    It required more code if you don't have __init__ yet, but you don't need to specify the widget.

    0 讨论(0)
  • 2021-02-02 11:29

    See the documentation

    class AuthorForm(ModelForm):
        class Meta:
            model = Author
            widgets = {
                'name': TextInput(attrs={'placeholder': 'name'}),
            }
    

    You could always create your own widget that derives from TextInput and includes the placeholder attribute, and use the widgets dictionary to simply map fields to your new widget without specifying the placeholder attribute for every field.

    0 讨论(0)
提交回复
热议问题