Django:无法在没有初始外键值的情况下验证表单

时间:2016-05-12 13:29:05

标签: python django

我在django views.py中有一个表单。

diagnosis.patientdemographics.patient_id的外键。

my_diagnosis表单无效,因为患者为空。有办法解决这个问题吗?

def input(request):

    context = RequestContext(request)
    print context
    ret = cache.get('input-rendered')

    if request.method == 'POST':

        my_demographics = DemographicForm(request.POST, prefix="demo")
        my_diagnosis = DiagnosisForm(request.POST, prefix='diag')


        if (my_demographics.is_valid() ):
            print "dem and diag validation"
            my_demographics_object = my_demographics.save(commit=False)
            my_demographics_object.author = request.user
            my_demographics_object.save()
            #my_diagnosis = DiagnosisForm(request.POST, prefix='diag', initial={'patient':my_demographics_object.patient_id} )

            print "my dem id"
            print my_demographics_object.patient_id
        if (my_diagnosis.is_valid()):
            my_diagnosis_object=my_diagnosis.save(commit=False)
            my_diagnosis_object.patient = my_demographics_object.patient_id
            my_diagnosis_object.author = request.user
            my_diagnosis_object.save()

这是Diagnosis中的forms.py表格:

class DiagnosisForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):

        super(DiagnosisForm, self).__init__(*args, **kwargs)

        self.fields['diagnosis_circumstances_date']= forms.DateField(label=('Date'),required=False,
        widget=DateTimePicker(options={"format": "YYYY-MM-DD",
                                       "pickTime": False,
                                       "startDate": "1900-01-01"}))


        self.helper=FormHelper(form=self)

        self.fields['icd_10_desc']= forms.ModelChoiceField(queryset=icd_10.objects.all(),
                                    widget=autocomplete_light.ChoiceWidget("icd_10Autocomplete"))
        self.fields['icd_10_desc'].label = "ICD-10 description"
        diagnosis_option_value = (
        ('b-thalassaemia syndromes', 'b-thalassaemia syndromes',),
        ('a-thalassaemia syndromes', 'a-thalassaemia syndromes'),
        ('Sickle cell syndromes', 'Sickle cell syndromes'),
        ('Other haemoglobin variants','Other haemoglobin variants'),
        ('Red cell membrane disorders','Red cell membrane disorders'),
        ('Red cell enzyme disorders','Red cell enzyme disorders'),
        ('Congenital dyserythropoietic anaemias','Congenital dyserythropoietic anaemias')
    )
        self.fields['diagnosis_option']=forms.MultipleChoiceField(choices=diagnosis_option_value, widget=forms.CheckboxSelectMultiple())



        diagnosis_circumstances_value = (
        ('Antenatal diagnosis','Antenatal diagnosis'),
        ('Neonatal diagnosis','Neonatal diagnosis'),
        ('By the presence of affected related','By the presence of affected related'),
        ('Clinical diagnosis', 'Clinical diagnosis'),
        ('Other','Other')

        )
        self.fields['diagnosis_circumstances']=forms.MultipleChoiceField(choices=diagnosis_circumstances_value, widget=forms.CheckboxSelectMultiple())
        #self.fields['patient'].queryset = Demographic.objects.filter(patient_id=self.instance.patient)
        self.helper.field_class = 'col-md-8'
        self.helper.label_class = 'col-md-3'

        #self.helper.form_class = 'forms-horizontal'
        self.helper.layout = Layout(
            Fieldset (
                # 'patient',
                '<b>Diagnosis information</b>',
                Div(
                    #HTML(u'<div class="col-md-2"></div>'),
                    Div('age_of_diagnosis',css_class='col-md-6'),
                    Div('age_at_onset_of_symptoms',css_class="col-md-6"),
                    css_class='row',
                    ),



                'diagnosis_option',
                'record_of_genotype',
                'icd_10_desc',
                'icd_10_code',
                'orpha_code',
                'comment',
                ),


            FormActions(
                Submit('submit', "Save changes"),
                Submit('cancel',"Cancel")
            ),
        )
        self.helper.form_tag = False
        self.helper.form_show_labels = True

    class Meta:
        model = Diagnosis
        exclude = ['patient']
        exclude = ('author',)
        list_display = ('title', 'pub_date', 'author')

这是my_diagnosis.errors

的结果
<ul class="errorlist"><li>patient<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

1 个答案:

答案 0 :(得分:1)

如果您在视图中设置患者,则只需将patient表单从模型表单的字段列表中删除:

DiagnosisForm(forms.ModelForm):
    class Meta:
        model = Diagnosis
        fields = ('myfield1', 'myfield2', ...)

如果您愿意,可以使用exclude

DiagnosisForm(forms.ModelForm):
    class Meta:
        model = Diagnosis
        exclude = ('author', 'patient',)

目前形式的问题是你有

    exclude = ['patient']
    exclude = ('author',)

第二个排除取代第一个排除。你应该:

    exclude = ['author', 'patient']

有关详细信息,请参阅selecting the fields to use上的模型表单文档。