class MaternalVisitForm(BaseConsentedModelForm): """Based on model visit. Attributes reason and info_source override those from the base model so that the choices can be custom for this app. """ reason = forms.ChoiceField( label='Reason for visit', choices=[choice for choice in VISIT_REASON], help_text= "If 'unscheduled', information is usually reported at the next scheduled visit, but exceptions may arise", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer), ) info_source = forms.ChoiceField( label='Source of information', choices=[choice for choice in VISIT_INFO_SOURCE], widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer), ) def clean(self): cleaned_data = self.cleaned_data """validate data""" if not cleaned_data.get('report_datetime'): raise forms.ValidationError( 'This field is required. Please fill it in') if cleaned_data.get('reason') == 'deferred': raise forms.ValidationError( 'Reason \'deferred\' is not valid for maternal visits. Please correct.' ) if cleaned_data.get('reason') == 'missed' and not cleaned_data.get( 'reason_missed'): raise forms.ValidationError( 'Please provide the reason the scheduled visit was missed') if cleaned_data.get('reason') != 'missed' and cleaned_data.get( 'reason_missed'): raise forms.ValidationError( "Reason for visit is NOT 'missed' but you provided a reason missed. Please correct." ) if cleaned_data.get('info_source') == 'OTHER' and not cleaned_data.get( 'info_source_other'): raise forms.ValidationError( "Source of information is 'OTHER', please provide details below your choice" ) if cleaned_data.get('vital status') and not cleaned_data.get( 'survival_status') and not cleaned_data.get('date_last_alive'): raise forms.ValidationError( "Visit reason is 'Vital Status', please enter Survival Status and Date Last Alive." ) #Meta data validations self.instance.recalculate_meta(MaternalVisit(**cleaned_data), forms.ValidationError) cleaned_data = super(MaternalVisitForm, self).clean() return cleaned_data class Meta: model = MaternalVisit
class InfantOffStudyForm (BaseOffStudyForm): reason = forms.ChoiceField( label='Please code the primary reason participant taken off-study', choices=[choice for choice in OFF_STUDY_REASON], help_text="", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer), ) def clean(self): cleaned_data = self.cleaned_data if not cleaned_data.get('registered_subject'): raise forms.ValidationError('This field is required. Please fill it in') if not cleaned_data.get('offstudy_date'): raise forms.ValidationError('This field is required. Please fill it in') #If Infant Drug has not been discontinued and infant is randomised, raise error infant_rando = InfantRando.objects.filter(subject_identifier=cleaned_data.get('registered_subject').subject_identifier) infant_off_drug = InfantOffDrug.objects.filter(registered_subject=cleaned_data.get('registered_subject')) if not infant_off_drug and infant_rando: raise forms.ValidationError('Please key in InfantOffDrug before keying in the Off-study form.') return super(InfantOffStudyForm, self).clean() class Meta: model = InfantOffStudy
class InfantOffStudyForm(BaseInfantModelForm): reason = forms.ChoiceField( label='Please code the primary reason participant taken off-study', choices=[choice for choice in OFF_STUDY_REASON], help_text="", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) class Meta: model = InfantOffStudy fields = '__all__' def clean(self): cleaned_data = super(InfantOffStudyForm, self).clean() # self.validate_offstudy_date() return cleaned_data def validate_offstudy_date(self): cleaned_data = self.cleaned_data maternal_subject_identifier = cleaned_data.get( 'infant_visit').appointment.registered_subject.relative_identifier maternal_consent = MaternalConsent.objects.filter( registered_subject__subject_identifier=maternal_subject_identifier ).order_by('consent_datetime').last() if cleaned_data.get( 'offstudy_date') < maternal_consent.consent_datetime.date(): raise forms.ValidationError( 'Off study date cannot be before consent date') if cleaned_data.get('offstudy_date') < maternal_consent.dob: raise forms.ValidationError( 'Off study date cannot be before date of birth')
class FornecedorAdminForm(forms.ModelForm): class Meta: model = Fornecedor fields = ('nome', 'identificador', 'dados_financeiros', 'servico_padrao', 'ativo', ) TIPO_CHOICES = ( ('PF', u'Pessoa Física'), ('PJ', u'Pessoa Jurídica'), ) tipo = forms.ChoiceField(widget=AdminRadioSelect(attrs={'class': 'radiolist inline'}), choices=TIPO_CHOICES, initial='PJ') identificador = forms.CharField(label=u'CPF/CNPJ', max_length=18) def _only_numbers(self, value): return ''.join(val for val in value if val.isdigit()) def clean_identificador(self): return self._only_numbers(self.cleaned_data.get('identificador')) def __init__(self, *args, **kwargs): super(FornecedorAdminForm, self).__init__(*args, **kwargs) identificador = self._only_numbers(self.instance.identificador) if args and args[0].get('identificador'): identificador = self._only_numbers(args[0].get('identificador')) if identificador: self.fields['tipo'].initial = 'PF' if len(identificador) == 11 else 'PJ' if self.fields['tipo'].initial == 'PF': self.fields['identificador'] = BRCPFField(label=u'CPF/CNPJ') else: self.fields['identificador'] = BRCNPJField(label=u'CPF/CNPJ')
class AccountCreationForm(forms.Form): provider = forms.ChoiceField( label=_('Provider'), choices=sorted(providers.as_choices(enabled_only=True), key=lambda provider: provider[1]), widget=AdminRadioSelect(attrs={'class': 'radiolist'}), error_messages={'required': _('Please select a provider.')})
class MaternalOffStudyForm(OffStudyFormMixin, BaseMaternalModelForm): reason = forms.ChoiceField( label='Please code the primary reason participant taken off-study', choices=[choice for choice in OFF_STUDY_REASON], help_text="", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) def clean(self): cleaned_data = super(MaternalOffStudyForm, self).clean() self.validate_offstudy_date() return cleaned_data def validate_offstudy_date(self): cleaned_data = self.cleaned_data subject_identifier = cleaned_data.get( 'maternal_visit').appointment.registered_subject.subject_identifier consent = MaternalConsent.objects.filter( maternal_eligibility__registered_subject__subject_identifier= subject_identifier).order_by('consent_datetime').first() if consent: if cleaned_data.get( 'offstudy_date') < consent.consent_datetime.date(): raise forms.ValidationError( "Off study date cannot be before consent date") if cleaned_data.get('offstudy_date') < consent.dob: raise forms.ValidationError( "Off study date cannot be before dob") else: raise forms.ValidationError('Maternal Consent does not exist.') class Meta: model = MaternalOffStudy fields = '__all__'
def formfield_for_choice_field(self, db_field, request=None, **kwargs): """ Get a form Field for a database Field that has declared choices. """ # If the field is named as a radio_field, use a RadioSelect if db_field.name == 'redirect_type': kwargs['widget'] = AdminRadioSelect( attrs={'class': get_ul_class(admin.VERTICAL)}) return db_field.formfield(**kwargs)
class MaternalRequisitionForm(RequisitionFormMixin): study_site = forms.ChoiceField( label='Study site', choices=STUDY_SITES, initial=settings.DEFAULT_STUDY_SITE, help_text="", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) def __init__(self, *args, **kwargs): super(MaternalRequisitionForm, self).__init__(*args, **kwargs) self.fields['item_type'].initial = 'tube' def clean(self): cleaned_data = super(MaternalRequisitionForm, self).clean() if cleaned_data.get('drawn_datetime'): if cleaned_data.get('drawn_datetime').date() < cleaned_data.get( 'requisition_datetime').date(): raise forms.ValidationError( 'Requisition date cannot be in future of specimen date. Specimen draw date is ' 'indicated as {}, whilst requisition is indicated as{}. Please correct' .format( cleaned_data.get('drawn_datetime').date(), cleaned_data.get('requisition_datetime').date())) if (cleaned_data.get('panel').name == 'Vaginal swab (Storage)' or cleaned_data.get('panel').name == 'Rectal swab (Storage)' or cleaned_data.get('panel').name == 'Skin Swab (Storage)' or cleaned_data.get('panel').name == 'Vaginal STI Swab (Storage)'): if cleaned_data.get('item_type') != 'swab': raise forms.ValidationError( 'Panel is a swab therefore collection type is swab. Please correct.' ) else: if cleaned_data.get('item_type') != 'tube': raise forms.ValidationError( 'Panel {} can only be tube therefore collection type is swab. ' 'Please correct.'.format(cleaned_data.get('panel').name)) maternal_visit = MaternalVisit.objects.get( appointment__registered_subject=cleaned_data.get( 'maternal_visit').appointment.registered_subject, appointment=cleaned_data.get('maternal_visit').appointment, appointment__visit_instance=cleaned_data.get( 'maternal_visit').appointment.visit_instance) if maternal_visit: if ((maternal_visit.reason == SCHEDULED or maternal_visit.reason == UNSCHEDULED) and cleaned_data.get('reason_not_drawn') == 'absent'): raise forms.ValidationError( 'Reason not drawn cannot be {}. Visit report reason is {}'. format(cleaned_data.get('reason_not_drawn'), maternal_visit.reason)) return cleaned_data class Meta: model = MaternalRequisition fields = '__all__'
class MediaFileContentAdminForm(ItemEditorForm): mediafile = forms.ModelChoiceField( queryset=MEDIAFILE_CLASS.objects.all(), widget=MediaFileWidget, label=_('media file')) position = forms.ChoiceField( choices=POSITION_CHOICES, initial=POSITION_CHOICES[0][0], label=_('position'), widget=AdminRadioSelect(attrs={'class': 'radiolist'}))
class MediaFileContentAdminForm(ItemEditorForm): mediafile = forms.ModelChoiceField(queryset=MediaFile.objects.all(), widget=MediaFileWidget, required=False) type = forms.ChoiceField(choices=TYPE_CHOICES, initial=TYPE_CHOICES[0][0], label=_('type'), widget=AdminRadioSelect(attrs={'class': 'radiolist'})) def __init__(self, *args, **kwargs): super(MediaFileContentAdminForm, self).__init__(*args, **kwargs) self.fields['richtext'].widget.attrs.update({'class': 'item-richtext'})
class DiscountBaseForm(forms.Form): discount_type = forms.ChoiceField( label=_('Discount type'), choices=((ABSOLUTE, _('absolute amount')), (RELATIVE, _('relative amount in percents'))), widget=AdminRadioSelect(), ) amount = forms.DecimalField( label=_('Amount or number of percents')) explanation = CourseDiscount._meta.get_field( 'explanation').formfield()
class Meta: model = Twitter fields = '__all__' error_messages = { 'account': { 'required': _('A connected account is required to display tweets.'), }, } widgets = { 'timeline_source': AdminRadioSelect(attrs={'class': 'radiolist'}) }
def formfield_for_foreignkey(self, db_field, request=None, **kwargs): db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ForeignKeyRawIdWidget( db_field.rel, self.admin_site, using=db) elif db_field.name in self.radio_fields: kwargs['widget'] = AdminRadioSelect(attrs={ 'class': get_ul_class(self.radio_fields[db_field.name]), }) kwargs['empty_label'] = db_field.blank and _('None') or None return db_field.formfield(**kwargs)
class PolymorphicModelChoiceForm(forms.Form): """ The default form for the ``add_type_form``. Can be overwritten and replaced. """ #: Define the label for the radiofield type_label = _("Type") ct_id = forms.ChoiceField(label=type_label, widget=AdminRadioSelect(attrs={'class': 'radiolist'})) def __init__(self, *args, **kwargs): # Allow to easily redefine the label (a commonly expected usecase) super(PolymorphicModelChoiceForm, self).__init__(*args, **kwargs) self.fields['ct_id'].label = self.type_label
class MaternalVisitForm (VisitFormMixin, BaseModelForm): participant_label = 'mother' study_status = forms.ChoiceField( label='What is the mother\'s current study status', choices=MATERNAL_VISIT_STUDY_STATUS, initial=ON_STUDY, help_text="", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) reason = forms.ChoiceField( label='Reason for visit', choices=[choice for choice in VISIT_REASON], help_text="", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) info_source = forms.ChoiceField( label='Source of information', required=False, choices=[choice for choice in VISIT_INFO_SOURCE], widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) def clean(self): cleaned_data = super(MaternalVisitForm, self).clean() instance = None if self.instance.id: instance = self.instance else: instance = MaternalVisit(**self.cleaned_data) instance.subject_failed_eligibility(forms.ValidationError) return cleaned_data class Meta: model = MaternalVisit fields = '__all__'
class MaternalOffStudyForm (OffStudyFormMixin, BaseMaternalModelForm): reason = forms.ChoiceField( label='Please code the primary reason participant taken off-study', choices=[choice for choice in OFF_STUDY_REASON], help_text="", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) def clean(self): cleaned_data = super(MaternalOffStudyForm, self).clean() self.validate_offstudy_date() return cleaned_data class Meta: model = MaternalOffStudy
class InfantFuDxItemsForm (BaseInfantModelForm): grade = forms.ChoiceField( label='Grade', choices=[choice for choice in GRADING_SCALE_234], help_text="Grade of worst episode (3 or 4). Some DX reportable at Grade 2", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) def clean(self): cleaned_data = super(InfantFuDxItemsForm, self).clean() infant_fu_dx = cleaned_data.get('infant_fu_dx') visit = infant_fu_dx.infant_visit if 'specify' in cleaned_data.get('fu_dx', None): if not cleaned_data.get('fu_dx_specify', None): raise forms.ValidationError('please specify \'%s\'' % (cleaned_data.get('fu_dx').replace('specify', ''),)) if cleaned_data.get('fu_dx', None): # check for grade 2 dx codes grade_2_reportable_dx = ['Hepatitis:Drug related', 'Rash'] if cleaned_data.get('fu_dx') not in grade_2_reportable_dx and cleaned_data.get('grade', None) == 2: raise forms.ValidationError('{dx} is not reportable at grade 2.'.format(dx=cleaned_data.get('fu_dx'))) # validating for eae report if cleaned_data.get('is_eae_required') == 'Yes' and not cleaned_data.get('eae_reference'): raise forms.ValidationError('If eae report is available, give the eae reference number.') if cleaned_data.get('is_eae_required') == 'No' and cleaned_data.get('eae_reference'): raise forms.ValidationError('The eae report is indicated as not required, yet the eae reference number is given. Please correct') # validating that dx_onsetdate is not greater than the visit date if visit and cleaned_data.get('onset_date') > visit.report_datetime.date(): raise forms.ValidationError("Onset date cannot be greater than the visit date. Please correct") # if hospitalized, response about hospitalization in InfantPhysical and infantfudxitems should be same if InfantFuPhysical.objects.filter(infant_visit=visit).exists(): infant_fu_physical = InfantFuPhysical.objects.get(infant_visit=visit) if infant_fu_physical.was_hospitalized != cleaned_data.get('was_hospitalized'): raise forms.ValidationError('Your response about hospitalization in InfantFuPhysical, and whether or not patient was hospitalized in this DX form are not the same. Please correct.') return cleaned_data class Meta: model = InfantFuDxItems
class ArticleCadastroForm(forms.ModelForm): class Meta: model = ArticleCadastro widgets = { 'header': CKEditorWidget(), 'content': CKEditorWidget(), } link = forms.ChoiceField( label=u'Cadastro de link?', required=False, choices=((True, u'Sim'), (False, u'Não')), widget=AdminRadioSelect(attrs={'class': 'radiolist inline'})) upload = forms.ImageField(label=u"Imagem", required=False) def clean_link(self): return bool(self.cleaned_data.get('link')) def clean_title(self): title = self.cleaned_data.get('title') link = self.cleaned_data.get('link') if link == False and not title: raise forms.ValidationError(u'Este campo é obrigatório.') return title def clean_content(self): content = self.cleaned_data.get('content') link = self.cleaned_data.get('link') if link == True: URLValidator()(content) return content def __init__(self, *args, **kwargs): super(ArticleCadastroForm, self).__init__(*args, **kwargs) self.fields['title'].required = False if self.instance.pk: self.fields['link'].initial = False if self.instance and str(self.instance.pk) == self.instance.slug: self.fields['link'].initial = True
class MaternalOffStudyForm(BaseOffStudyForm): reason = forms.ChoiceField( label='Please code the primary reason participant taken off-study', choices=[choice for choice in OFF_STUDY_REASON], help_text="", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer), ) def clean(self): cleaned_data = self.cleaned_data if not cleaned_data.get('maternal_visit') or not cleaned_data.get( 'registered_subject'): raise forms.ValidationError( 'This field is required. Please fill it in') if not cleaned_data.get('offstudy_date'): raise forms.ValidationError( 'This field is required. Please fill it in') return cleaned_data class Meta: model = MaternalOffStudy
class HnsccRequisitionForm(BaseRequisitionForm): reason_not_drawn = forms.ChoiceField( label='If not drawn, please explain', choices=[choice for choice in REASON_NOT_DRAWN], required=False, widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer), ) def __init__(self, *args, **kwargs): super(HnsccRequisitionForm, self).__init__(*args, **kwargs) self.fields['item_type'].initial = 'tube' def clean(self): super(HnsccRequisitionForm, self).clean() cleaned_data = self.cleaned_data return cleaned_data class Meta: model = HnsccRequisition
class VideoContentAdminForm(ItemEditorForm): position = forms.ChoiceField( choices=TYPE_CHOICES, initial=TYPE_CHOICES[0][0], label=_('position'), widget=AdminRadioSelect(attrs={'class': 'radiolist'}))
def test_no_can_add_related(self): rel = models.Inventory._meta.get_field('parent').rel w = AdminRadioSelect() # Used to fail with a name error. w = RelatedFieldWidgetWrapper(w, rel, admin.site) self.assertFalse(w.can_add_related)
class SelectSiteForm(forms.Form): site = forms.ChoiceField( label=_('Site'), widget=AdminRadioSelect(attrs={'class': 'radiolist'}))
class MaternalConsentForm(BaseConsentForm): study_site = forms.ChoiceField( label='Study site', choices=STUDY_SITES, initial=settings.DEFAULT_STUDY_SITE, help_text="", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) def clean(self): self.cleaned_data['gender'] = FEMALE cleaned_data = super(MaternalConsentForm, self).clean() if cleaned_data.get('identity_type') == OMANG and cleaned_data.get( 'identity')[4] != '2': raise forms.ValidationError( 'Identity provided indicates participant is Male. Please correct.' ) eligibility = MaternalEligibility.objects.get( registered_subject=cleaned_data.get('registered_subject')) if cleaned_data.get('citizen') != eligibility.has_omang: raise forms.ValidationError( "In eligibility you said has_omang is {}. Yet you wrote citizen is {}. " "Please correct.".format(eligibility.has_omang, cleaned_data.get('citizen'))) self.validate_eligibility_age() self.validate_recruit_source() self.validate_recruitment_clinic() return cleaned_data def validate_eligibility_age(self): cleaned_data = self.cleaned_data try: identity = cleaned_data.get('identity') consent_v1 = MaternalConsent.objects.get(identity=identity, version=1) consent_age = relativedelta(consent_v1.consent_datetime.date(), consent_v1.dob).years except MaternalConsent.DoesNotExist: consent_age = relativedelta(timezone.now().date(), cleaned_data.get('dob')).years eligibility_age = MaternalEligibility.objects.get( registered_subject=cleaned_data.get( 'registered_subject')).age_in_years if consent_age != eligibility_age: raise forms.ValidationError( 'In Maternal Eligibility you indicated the participant is {}, ' 'but age derived from the DOB is {}.'.format( eligibility_age, consent_age)) def validate_recruit_source(self): cleaned_data = self.cleaned_data if cleaned_data.get('recruit_source') == OTHER: if not cleaned_data.get('recruit_source_other'): self._errors["recruit_source_other"] = ErrorList( ["Please specify how you first learnt about the study."]) raise forms.ValidationError( 'You indicated that mother first learnt about the study from a source other' ' than those in the list provided. Please specify source.') else: if cleaned_data.get('recruit_source_other'): self._errors["recruit_source_other"] = ErrorList([ "Please do not specify source you first learnt about" " the study from." ]) raise forms.ValidationError( 'You CANNOT specify other source that mother learnt about the study from ' 'as you already indicated {}'.format( cleaned_data.get('recruit_source'))) def validate_recruitment_clinic(self): cleaned_data = self.cleaned_data if cleaned_data.get('recruitment_clinic') == OTHER: if not cleaned_data.get('recruitment_clinic_other'): self._errors["recruitment_clinic_other"] = ErrorList( ["Please specify health facility."]) raise forms.ValidationError( 'You indicated that mother was recruited from a health facility other ' 'than that list provided. Please specify that health facility.' ) else: if cleaned_data.get('recruitment_clinic_other'): self._errors["recruitment_clinic_other"] = ErrorList( ["Please do not specify health facility."]) raise forms.ValidationError( 'You CANNOT specify other facility that mother was recruited from as you ' 'already indicated {}'.format( cleaned_data.get('recruitment_clinic'))) class Meta: model = MaternalConsent fields = '__all__'
class ArticleCategoryListForm(ItemEditorForm): layout = forms.ChoiceField( choices=LAYOUT_CHOICES, initial=LAYOUT_CHOICES[0][0], label=_('Layout'), widget=AdminRadioSelect(attrs={'class': 'radiolist'}))
class InfantVisitForm(VisitFormMixin, BaseModelForm): participant_label = 'infant' information_provider = forms.ChoiceField( label= 'Please indicate who provided most of the information for this infant\'s visit', choices=INFO_PROVIDER, initial='MOTHER', widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) study_status = forms.ChoiceField( label='What is the infant\'s current study status', choices=INFANT_VISIT_STUDY_STATUS, initial=ON_STUDY, widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) reason = forms.ChoiceField( label='Reason for visit', choices=[choice for choice in VISIT_REASON], widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) info_source = forms.ChoiceField( required=False, label='Source of information', choices=[choice for choice in VISIT_INFO_SOURCE], widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) def clean(self): cleaned_data = super(InfantVisitForm, self).clean() self.validate_current_consent_version() # self.validate_reason_visit_missed() # self.validate_report_datetime_and_consent() # self.validate_information_provider_is_alive() return cleaned_data def validate_report_datetime_and_consent(self): cleaned_data = self.cleaned_data try: relative_identifier = cleaned_data.get( 'appointment').registered_subject.relative_identifier maternal_consent = MaternalConsent.objects.filter( registered_subject__subject_identifier=relative_identifier ).order_by('consent_datetime').last() if cleaned_data.get( "report_datetime") < maternal_consent.consent_datetime: raise forms.ValidationError( "Report datetime cannot be before consent datetime") if cleaned_data.get( "report_datetime").date() < maternal_consent.dob: raise forms.ValidationError( "Report datetime cannot be before DOB") except MaternalConsent.DoesNotExist: raise forms.ValidationError('Maternal consent does not exist.') def validate_information_provider_is_alive(self): cleaned_data = self.cleaned_data try: if cleaned_data.get('information_provider') == 'MOTHER': relative_identifier = cleaned_data.get( 'appointment').registered_subject.relative_identifier maternal_death_report = MaternalDeathReport.objects.get( maternal_visit__appointment__registered_subject__subject_identifier =relative_identifier, death_date__lte=cleaned_data.get("report_datetime").date()) raise forms.ValidationError( 'The mother was reported deceased on {}.' 'The information provider cannot be the \'mother\'.'. format( maternal_death_report.death_date.strftime('%Y-%m-%d'))) except MaternalDeathReport.DoesNotExist: pass def validate_current_consent_version(self): try: td_consent_version = TdConsentVersion.objects.get( maternal_eligibility=self.maternal_eligibility) except TdConsentVersion.DoesNotExist: raise forms.ValidationError( 'Complete mother\'s consent version form before proceeding') else: try: MaternalConsent.objects.get( maternal_eligibility=self.maternal_eligibility, version=td_consent_version.version) except MaternalConsent.DoesNotExist: raise forms.ValidationError( 'Maternal Consent form for version {} before proceeding'. format(td_consent_version.version)) @property def maternal_eligibility(self): cleaned_data = self.cleaned_data relative_identifier = cleaned_data.get( 'appointment').registered_subject.relative_identifier try: return MaternalEligibility.objects.get( registered_subject__subject_identifier=relative_identifier) except MaternalEligibility.DoesNotExist: pass class Meta: model = InfantVisit fields = '__all__'
class InfantRequisitionForm(RequisitionFormMixin): study_site = forms.ChoiceField( label='Study site', choices=STUDY_SITES, initial=settings.DEFAULT_STUDY_SITE, help_text="", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) def __init__(self, *args, **kwargs): super(InfantRequisitionForm, self).__init__(*args, **kwargs) self.fields['item_type'].initial = 'tube' def clean(self): cleaned_data = super(InfantRequisitionForm, self).clean() self.validate_requisition_and_drawn_datetime() self.validate_sample_swabs() self.validate_dna_pcr_and_cytokines() self.validate_stool_sample_collection() self.validate_requisition_and_infant_visit() return cleaned_data def validate_requisition_and_drawn_datetime(self): cleaned_data = self.cleaned_data if cleaned_data.get('drawn_datetime'): if cleaned_data.get('drawn_datetime').date() < cleaned_data.get( 'requisition_datetime').date(): raise forms.ValidationError( 'Requisition date cannot be in future of specimen date. Specimen draw date is ' 'indicated as {}, whilst requisition is indicated as{}. Please correct' .format( cleaned_data.get('drawn_datetime').date(), cleaned_data.get('requisition_datetime').date())) def validate_sample_swabs(self): cleaned_data = self.cleaned_data if cleaned_data.get('panel').name == 'Rectal swab (Storage)': if cleaned_data.get('item_type') != 'swab': raise forms.ValidationError( 'Panel {} is a swab therefore collection type is swab. Please correct.' .format(cleaned_data.get('panel').name)) def validate_dna_pcr_and_cytokines(self): cleaned_data = self.cleaned_data if cleaned_data.get('panel').name in [ 'DNA PCR', 'Inflammatory Cytokines' ]: if cleaned_data.get('item_type') not in ['dbs', 'tube']: raise forms.ValidationError( 'Panel {} collection type can only be dbs or tube. ' 'Please correct.'.format(cleaned_data.get('panel').name)) def validate_stool_sample_collection(self): cleaned_data = self.cleaned_data sample_collection = InfantStoolCollection.objects.filter( infant_visit=cleaned_data.get('infant_visit')) if sample_collection: sample_collection = InfantStoolCollection.objects.get( infant_visit=cleaned_data.get('infant_visit')) if sample_collection.sample_obtained == YES: if (cleaned_data.get("panel").name == 'Stool storage' and cleaned_data.get("is_drawn") == NO): raise forms.ValidationError( "Stool Sample Collected. Stool Requisition is_drawn" " cannot be NO.") def validate_requisition_and_infant_visit(self): cleaned_data = self.cleaned_data if (cleaned_data.get('infant_visit').is_present == YES and cleaned_data.get('reason_not_drawn') == 'absent'): raise forms.ValidationError( 'Reason not drawn cannot be absent. On the visit report you said infant is present.' ' Please Correct.') class Meta: model = InfantRequisition
class MaternalVisitForm(VisitFormMixin, BaseModelForm): participant_label = 'mother' study_status = forms.ChoiceField( label='What is the mother\'s current study status', choices=MATERNAL_VISIT_STUDY_STATUS, initial=ON_STUDY, help_text="", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) reason = forms.ChoiceField( label='Reason for visit', choices=[choice for choice in VISIT_REASON], help_text="", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) info_source = forms.ChoiceField( label='Source of information', required=False, choices=[choice for choice in VISIT_INFO_SOURCE], widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer)) def clean(self): cleaned_data = super(MaternalVisitForm, self).clean() self.validate_current_consent_version() instance = None if self.instance.id: instance = self.instance else: instance = MaternalVisit(**self.cleaned_data) instance.subject_failed_eligibility(forms.ValidationError) self.clean_ultrasound_form(cleaned_data) # self.check_creation_of_antenatal_visit_2(cleaned_data) return cleaned_data def get_consent(self, registered_subject): """Return an instance of the consent model. If no consent model is defined, as with infants, try for the birth_model.""" try: consent = self._meta.model.consent_model.objects.get( subject_identifier=registered_subject.subject_identifier) except self._meta.model.consent_model.MultipleObjectsReturned: consent = self._meta.model.consent_model.objects.filter( subject_identifier=registered_subject.subject_identifier ).order_by('version').first() except ObjectDoesNotExist: raise forms.ValidationError( '\'{}\' does not exist for subject.'.format( self._meta.model.consent_model._meta.verbose_name)) except AttributeError: consent = self.get_birth_model_as_consent(registered_subject) return consent def validate_current_consent_version(self): try: td_consent_version = TdConsentVersion.objects.get( maternal_eligibility=self.maternal_eligibility) except TdConsentVersion.DoesNotExist: raise forms.ValidationError( 'Complete mother\'s consent version form before proceeding') else: try: MaternalConsent.objects.get( maternal_eligibility=self.maternal_eligibility, version=td_consent_version.version) except MaternalConsent.DoesNotExist: raise forms.ValidationError( 'Maternal Consent form for version {} before proceeding'. format(td_consent_version.version)) @property def maternal_eligibility(self): cleaned_data = self.cleaned_data subject_identifier = cleaned_data.get( 'appointment').registered_subject.subject_identifier try: return MaternalEligibility.objects.get( registered_subject__subject_identifier=subject_identifier) except MaternalEligibility.DoesNotExist: return # def get_birth_model_as_consent(self, registered_subject): # """Return the birth model in place of the consent_model.""" # try: # birth_model = self._meta.model.birth_model.objects.get( # subject_identifier=registered_subject.subject_identifier) # except ObjectDoesNotExist: # raise forms.ValidationError( # '\'{}\' does not exist for subject.'.format(self._meta.model.consent_model._meta.verbose_name)) # return birth_model def clean_ultrasound_form(self, cleaned_data): registered_subject = cleaned_data['appointment'].registered_subject if cleaned_data['appointment'].visit_definition.code == '1020M': try: MaternalUltraSoundInitial.objects.get( maternal_visit__appointment__registered_subject= registered_subject) except MaternalUltraSoundInitial.DoesNotExist: raise forms.ValidationError( 'Please ensure you have filled Maternal Ultrasound Initial Form before' ' continuing.') def check_creation_of_antenatal_visit_2(self, cleaned_data): appointment = cleaned_data.get('appointment') if appointment.visit_definition.code == '1020M': gestational_age = MaternalUltraSoundInitial.objects.get( maternal_visit__appointment__registered_subject=appointment. registered_subject) gestational_age = gestational_age.evaluate_ga_confirmed() if gestational_age < 32: raise forms.ValidationError( 'Antenatal Visit 2 cannot occur before 32 weeks. Current GA is "{}" weeks' .format(gestational_age)) class Meta: model = MaternalVisit fields = '__all__'
class InfantVisitForm(BaseInfantModelForm): """Based on model maternal_visit. Attributes reason and info_source override those from the base model so that the choices can be custom for this app. """ reason = forms.ChoiceField( label='Reason for visit', choices=[choice for choice in VISIT_REASON], help_text= "If 'unscheduled', information is usually reported at the next scheduled visit, but exceptions may arise", widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer), ) info_source = forms.ChoiceField( label='Source of information', choices=[choice for choice in VISIT_INFO_SOURCE], widget=AdminRadioSelect(renderer=AdminRadioFieldRenderer), ) def clean(self): cleaned_data = self.cleaned_data """validate data""" if not cleaned_data.get('appointment'): raise forms.ValidationError( 'This field is required. please fill it in') if cleaned_data.get('reason') == 'deferred': if cleaned_data.get('appointment').visit_definition.code != '2010': raise forms.ValidationError( 'Reason \'deferred\' may only be used on visit 2010. Please correct.' ) if cleaned_data.get('reason') == 'missed' and not cleaned_data.get( 'reason_missed'): raise forms.ValidationError( 'Please provide the reason the scheduled visit was missed') if cleaned_data.get('reason') != 'missed' and cleaned_data.get( 'reason_missed'): raise forms.ValidationError( "Reason for visit is NOT 'missed' but you provided a reason missed. Please correct." ) if cleaned_data.get('info_source') == 'OTHER' and not cleaned_data.get( 'info_source_other'): raise forms.ValidationError( "Source of information is 'OTHER', please provide details below your choice" ) if not cleaned_data.get('report_datetime'): raise forms.ValidationError( "Please fill in the Date and Time of visit.") if cleaned_data.get( 'survival_status' ) == 'DEAD' and not cleaned_data.get('date_last_alive'): raise forms.ValidationError( 'Please provide date information, when infant was last known to be alive' ) if cleaned_data.get('reason') == 'death' and cleaned_data.get( 'info_source') == 'telephone': raise forms.ValidationError( "If visit reason is death, info source cannot be {}. Please select another info source or 'Other contact with participant (for example telephone call)' if it is telephone" ) if cleaned_data.get('reason') == 'missed' and cleaned_data.get( 'report_datetime').date() >= date(2015, 4, 7): raise forms.ValidationError( 'Visit Report reason CANNOT be missed for any date after 07-04-2015' ) # check study status study_status_display = [ choice[1] for choice in InfantVisit._meta.get_field('study_status').choices if choice[0] == cleaned_data.get('study_status') ] if re.search('onstudy', cleaned_data.get('study_status')): registered_subject = cleaned_data.get( 'appointment').registered_subject # check birth if not InfantBirth.objects.filter( registered_subject=registered_subject): # not born, cannot be on study raise forms.ValidationError( "Study status cannot be 'On Study'. Infant Birth Record not available. You wrote %s" % study_status_display) elif re.search('drug', cleaned_data.get('study_status')): if not registered_subject.sid: # not on drug, etc because has not rando'ed raise forms.ValidationError( "Infant has not yet randomized. Study status cannot be 'On Drug', 'Off Drug' or 'Not Yet Started Drug'. You wrote %s" % study_status_display) elif re.search('notrando', cleaned_data.get('study_status')): if registered_subject.sid: # is rando'ed, so no... raise forms.ValidationError( "Infant is randomized. Please choose the correct study status. You wrote %s" % study_status_display) #validate that you cant save infant visit greater that 2000 if infant eligibility has not been filled in self.instance.requires_infant_eligibility(InfantVisit(**cleaned_data), forms.ValidationError) #Meta data validations self.instance.recalculate_meta(InfantVisit(**cleaned_data), forms.ValidationError) #validate that you cant save infant visit if previous visit has not been saved. self.instance.check_previous_visit_keyed(InfantVisit(**cleaned_data), forms.ValidationError) return super(InfantVisitForm, self).clean() class Meta: model = InfantVisit