Django does not add attribute to the custom ModelForm widget

后端 未结 1 1495
清酒与你
清酒与你 2021-01-28 05:50

models.py

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


        
1条回答
  •  再見小時候
    2021-01-28 06:39

    The widgets option is for overriding the defaults. It doesn't work for your tos field because you have declared tos = BooleanField() in your form. See the note in the widgets docs for more information about this.

    You can fix the issue by passing widget when you declare the tos field:

    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'}),
            }
    

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