【问题标题】:Django forms.ModelForm - placeholder not showingDjango forms.ModelForm - 占位符不显示
【发布时间】:2019-04-21 02:42:57
【问题描述】:

我的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 表单字段。有人可以分享一些关于我在这里做错了什么的信息吗?

【问题讨论】:

    标签: django django-forms modelform


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2015-03-16
      • 2016-04-03
      • 1970-01-01
      • 2016-10-04
      • 2017-09-19
      • 2019-09-29
      • 2014-12-07
      • 1970-01-01
      相关资源
      最近更新 更多