Django不会向自定义ModelForm小部件添加属性

时间:2017-11-29 17:57:51

标签: python django django-forms

models.py

class MyModel(models.Model):
    pub_date = models.DateTimeField(default=timezone.now)
    title = models.CharField(max_length=255, blank=False, null=False)
    text = models.TextField(blank=True, null=True)

forms.py

class MyModelForm(ModelForm):
    tos = BooleanField()
    class Meta:
        model = models.MyModel
        fields = ['title', 'text', 'tos']
        widgets = {
            'title': TextInput(attrs={'class': 'form-control', 'placeholder': 'Title'}),
            'text': Textarea(attrs={'class': 'form-control', 'placeholder': 'Text'}),
            'tos': CheckboxInput(attrs={'data-validation-error-msg': 'You have to agree to our terms and conditions'}),
        }

结果:

>>> print(forms.MyModelForm())
<tr><th><label for="id_title">Title:</label></th><td><input type="text" name="title" class="form-control" placeholder="Title" maxlength="255" required id="id_title" /></td></tr>
<tr><th><label for="id_text">Text:</label></th><td><textarea name="text" cols="40" rows="10" class="form-control" placeholder="Text" id="id_text"></textarea></td></tr>
<tr><th><label for="id_tos">Tos:</label></th><td><input type="checkbox" name="tos" required id="id_tos" /></td></tr>

您可以看到TOS字段中缺少data-validation-error-msg属性。

有什么想法吗?

修改

这有效:

class MyModelForm(ModelForm):
    tos = BooleanField(
        widget=CheckboxInput(
            attrs={'data-validation-error-msg': 'You have to agree to our terms and conditions'}))
    class Meta:
        model = models.MyModel
        fields = ['title', 'text', 'tos']
        widgets = {
            'title': TextInput(attrs={'class': 'form-control', 'placeholder': 'Title'}),
            'text': Textarea(attrs={'class': 'form-control', 'placeholder': 'Text'}),
        }

它与Meta类不兼容仍然很奇怪。

1 个答案:

答案 0 :(得分:0)

widgets选项用于覆盖默认值。它不适用于您的tos字段,因为您已在表单中声明tos = BooleanField()。有关详细信息,请参阅widgets docs中的注释。

您可以在声明widget字段时传递tos来解决问题:

class MyModelForm(ModelForm):
    tos = BooleanField(widget=CheckboxInput(attrs={'data-validation-error-msg': 'You have to agree to our terms and conditions'}))
    class Meta:
        model = models.MyModel
        fields = ['title', 'text', 'tos']
        widgets = {
            'title': TextInput(attrs={'class': 'form-control', 'placeholder': 'Title'}),
            'text': Textarea(attrs={'class': 'form-control', 'placeholder': 'Text'}),
        }