I have a visit-create class based on a CreateView. It accesses the organization from the URL, so it's passed in as a keyword arg.
class VisitCreate(LoginRequiredMixin, UserOrgRequiredMixin, CreateView):
model = models.Visit
form_class = VisitCreateForm
# template_name is "visit_form.html" from CreateView
def form_valid(self, form):
# get the patient for this visit
patient = models.Patient.get_by_pk(self.kwargs['patientId'])
if not patient or patient.organization.name != self.kwargs['orgStr']:
raise SuspiciousOperation('Patient does not exist')
I want to write a form field validator that checks something about the visit, but it needs the orgStr. Here is the current form field validator, but it can't get the orgStr:
class VisitCreateForm(ModelForm):
class Meta:
model = models.Visit
...
# Allow only one visit per day
def clean_visit_date(self):
visit_date = self.cleaned_data['visit_date']
if models.Visit.get_visits(visit_date, visit_date, self.kwargs['orgStr']):
raise ValidationError('There is already a visit on this date')
How do I mark a field error on visit_date? Either I have to pass orgStr to the form somehow, or mark the field error in VisitCreate.form_valid.
Please don't suggest adding the orgStr as a hidden field in the form. That seems crazy.
form_valid()method withform.add_error(...), but then you need to handle your invalid form (e.g. by returningself.form_invalid(...)), which complicates the flow of the code.