pythondjangoformsdjango-forms

'BooleanField' object has no attribute 'use_required_attribute' in django


as the title says i am getting the error while i am using a booleanfield:

'BooleanField' object has no attribute 'use_required_attribute' in django

Models.py

class contactData(models.Model):

    ...
    mapActivated         = models.BooleanField(default=True)

forms.py:

class ContactForm(forms.ModelForm):

class Meta:
    model = contactData
    fields = [
        'vision',
        'horario',
        'image_path',
        'mapActivated',
        ]
    labels = {
        'image_path': '',    
    }

    widgets = {
        'mapActivated': forms.BooleanField(required=True)
    }

Anyone can help me with this?

Thank you!


Solution

  • You are confusing form fields with form widgets. A forms.BooleanField [Django-doc] is not a widget, it is a form field. A widget is for example the CheckboxInput [Django-doc], it specifies how to render that in a HTML form.

    You can specify the field as:

    class ContactForm(forms.ModelForm):
        mapActivated = forms.BooleanField(required=True)
    
        class Meta:
            model = contactData
            fields = [
                'vision',
                'horario',
                'image_path',
                'mapActivated',
            ]
            labels = {
                'image_path': '',    
            }

    By setting this as required=True, you require that the user will check the checkbox. This might not be (per se) what you want to do. If the user has the freedom to check/uncheck it. Removing required=True should be sufficient.