简体   繁体   中英

Django make Boolean Field required for CreateView

I have a model where I need to user to tick the Checkbox before proceeding. If the checkbox is not checked the browser should not allow the user to continue with form submission (simple, right?)

I'm using a CreateView to handle this model and ... it doesn't work - one can submit the form without ticking the checkbox (the patient_agreement BooleanField).

How to make this check-box required for this CreateView CBV?

Here's my model:

class Patient(models.Model):

    name = models.CharField(max_length=30, blank=False, verbose_name=_('Name'))
    surname = models.CharField(max_length=70, blank=False, verbose_name=_("Surname"))
    patient_agreement = models.BooleanField(
          blank=False,
          verbose_name=_("Patient has been notified about GDPR and his right to his data"),
          help_text=_("Mark only if you have informed the patient about his rights in the GDPR context"),

    )

And this is my view:

class NewPatientFormView(LoginRequiredMixin, CreateView):
    model = Patient
    fields = ['name', 'surname','patient_agreement']

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.created_by_user = self.request.user
        # self.object.save()
        return super().form_valid(form)

How to make the checkbox required before the form can be submitted?!

My suggestion would be to add a custom validation method for the field in the form that requires it to equal True for validation to pass.

## forms.py

class PatientForm(Form):

...

    def clean_patient_agreement(self):
        pa_value = self.cleaned_data.get('patient_agreement',False)

        ## Return value if True (checked)
        if pa_value:
            return pa_value

        ## Raise exception if not checked
        raise ValidationError('Must check patient agreement box to proceed')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM