具有用户定义字段和外键选择的ModelForm

时间:2018-07-06 09:01:53

标签: python django django-forms

在我的应用中,我以Study作为中心模型。 Study个具有多个Strata,每个Strata具有多个Level。用户通过为与该研究相关联的每个Allocation选择一个级别来为研究创建Strata,例如:

class Study(models.Model):
    name = models.CharField(max_length=100)

class Stratum(models.Model):
    study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='strata')
    name = models.CharField(max_length=100)

class Level(models.Model):
    stratum = models.ForeignKey(Stratum, on_delete=models.CASCADE, related_name='levels')
    label = models.CharField(max_length=100)

class Allocation(models.Model):
    study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='allocations')
    code = models.CharField(blank=False, max_length=100)
    levels = models.ManyToManyField(Level, related_name='allocations')

为了为分配创建表单创建字段,我目前在表单的构造函数中找到所有Strata和关联的级别,但是由于用户不与之交互而隐藏了层次:

class AllocationForm(forms.ModelForm):

    class Meta:
        model = Allocation
        fields = ('code',)

    def __init__(self, *args, **kwargs):
        study = kwargs.pop('study')
        super(AllocationForm, self).__init__(*args, **kwargs)

        strata = Stratum.objects.filter(study=study)

        for stratum in strata:
            self.fields[stratum.name] = forms.IntegerField(
                widget=forms.HiddenInput()
            )
            self.fields[stratum.name].initial = stratum.id
            self.fields[stratum.name].disabled = True

            self.fields[stratum.name + '_level'] = forms.ModelChoiceField(
                queryset=Level.objects.filter(stratum=stratum)
            )

这是将关联对象附加到表单的安全且明智的方法吗?我担心在尝试创建分配时将无法跟踪StrataLevel之间的连接。在视图中这样做会更好吗?

0 个答案:

没有答案