2016-12-16 78 views
0

我對Django仍然很缺乏經驗,但我在這個問題上陷入困境。我得到了一個幾乎完成的項目,父母可以在他們的孩子上填寫評估,然後研究人員可以使用Django和Postgresql收集和存儲這些數據。有兩個不同的應用程序有幾個相關的模型,它們都與另一個相關。 「儀器」(測試類型)可以有多個研究,而這些研究又可以有多個參與者。我做了一個很糟糕的圖像來描述我的意思。基於遠程相關模型的Django表單驗證

有一種形式,BackgroundForm,收集人口統計信息(年齡,出生體重等)。然後將此數據存儲在模型中,使用參與者的管理標識BackgroundInfo。我遇到的問題使表單驗證更加靈活。某些儀器(測試)是針對特定年齡的,我不確定如何將這些信息一直提供給BackgroundForm驗證,因爲這些信息位於幾個關係之外。有沒有一種方法來啓用表單驗證,根據位於幾個關係之外的模型的屬性進行驗證?

Map of Django site

cdi_forms/forms.py

class BackgroundForm(BetterModelForm): 
    age = forms.IntegerField() 
    sex = forms.ChoiceField(choices=(('M', 'Male'), ('F', 'Female'), ('O', 'Other')), widget=forms.RadioSelect) 

    def clean(self): 
     cleaned_data = super(BackgroundForm, self).clean() 
     if cleaned_data.get('age') == '': 
      self.add_error('age', 'Please enter your child\'s DOB in the field above.') 

    class Meta: 
     model = BackgroundInfo 
     exclude = ['administration'] 

cdi_forms/models.py

class BackgroundInfo(models.Model): 
    administration = models.OneToOneField("researcher_UI.administration") 
    age = models.IntegerField(verbose_name = "Age (in months)") 
    sex = models.CharField(max_length = 1, choices = (('M', "Male"), ('F', "Female"), ('O', "Other"))) 

researcher_UI/models.py

class administration(models.Model): 
    study = models.ForeignKey("study") 
    subject_id = models.IntegerField() 

class study(models.Model): 
    researcher = models.ForeignKey("auth.user") 
    name = models.CharField(max_length = 51) 
    instrument = models.ForeignKey("instrument") 

class instrument(models.Model): 
    name = models.CharField(max_length = 51, primary_key=True) 
    language = models.CharField(max_length = 51, blank = True) 
    min_age = models.IntegerField(verbose_name = "Minimum age", null = True) 
    max_age = models.IntegerField(verbose_name = "Maximum age", null = True) 

回答

0

沒關係!我做了一些更多的搜索,我能夠找到這個page。基本上,我在views.py中抓取了我想要的參數,並將它們傳遞給我的表單。

cdi_forms/views.py

def background_info_form(request, hash_id): 
    administration_instance = administration.objects.get(url_hash = hash_id) # Each test has it's own URL identifier 
    min_age = administration_instance.study.instrument.min_age 
    max_age = administration_instance.study.instrument.max_age 
    ... 
    background_form = BackgroundForm(request.POST, instance = background_instance, min_age = min_age, max_age = max_age) 

cdi_forms/forms.py

class BackgroundForm(BetterModelForm): 
    age = forms.IntegerField() 
    ... 
    def __init__(self, *args, **kwargs): 
     self.min_age = kwargs.pop('min_age', None) 
     self.max_age = kwargs.pop('max_age', None) 
     super(BackgroundForm, self).__init__(*args, **kwargs) 
    ... 
    def clean(self): 
     #Now I can compare my age field to self.min_age and self.max_age