Django Forms.ModelForm-占位符未显示

时间:2019-04-21 02:42:58

标签: django django-forms modelform

我的forms.py中有以下代码:

class CandidateSignUpForm(forms.ModelForm):
first_name = forms.CharField(max_length=50)
last_name = forms.CharField(max_length=50)

class Meta:
    model = User
    fields = ('__all__')
    widgets = {
        'first_name': forms.TextInput(
            attrs = {
                'placeholder':'Ime',
                'class': 'validate'
            },
        ),

        'last_name': forms.TextInput(
            attrs = {
                'placeholder': _('Prezime'),
                'class': 'validate'
            },
        ),

        'email': forms.EmailInput(
            attrs = {
                'placeholder': _('E-mail'),
                'class': 'validate'
            },
        ),

        'password': forms.PasswordInput(
            attrs = {
                'placeholder': _('Lozinka'),
                'class': 'validate'
            },
        ),

    }

模板中的部分只是{{ form.first_name }}。现在,占位符不适用于first_namelast_name表单域,但适用于email表单域。有人可以分享一些有关我在这里做错了什么的信息吗?

1 个答案:

答案 0 :(得分:1)

由于您已经在类本身中指定了字段,因此您应该使用嵌入式窗口小部件(因为Meta小部件字段用于覆盖默认小部件)。

class CandidateSignUpForm(forms.ModelForm):
    first_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': 'Ime', 'class': 'validate'}))
    last_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': _('Prezime'), 'class': 'validate'}))

    class Meta:
        ...
  

https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#overriding-the-default-fields