[英]The proper Django way to make a form field required on CreateView, but optional on UpdateView?
[英]Django make Boolean Field required for CreateView
我有一個模型,需要用戶在繼續之前選中復選框。 如果未選中該復選框,則瀏覽器不應允許用戶繼續提交表單(簡單,對吧?)
我正在使用CreateView來處理此模型,但它不起作用-可以在不勾選復選框的情況下提交表單( patient_agreement
BooleanField)。
如何使此CreateView CBV需要此復選框?
這是我的模型:
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"),
)
這是我的觀點:
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)
如何在提交表單之前選中所需的復選框?
我的建議是為表單中的字段添加自定義驗證方法,該方法要求它等於True才能通過驗證。
## 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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.