提问人:Marius 提问时间:7/6/2018 更新时间:7/6/2018 访问量:35
具有用户定义字段和外键选项的 ModelForm
ModelForm with user-defined fields and choices from foreign keys
问:
在我的应用程序中,我有作为中心模型。s 有多个 ,每个有多个 s。用户通过为链接到该研究的每个级别选择一个级别来为该研究创建 s,例如: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)
)
这是将关联对象附加到表单的安全且明智的方法吗?我担心在尝试创建分配时会忘记 和 s 之间的联系。这在视图中会更好吗?Strata
Level
答: 暂无答案
评论