我尝试使用inlineformset,并且在此实例中,某些字段对于此特定用户将是相同的。我想初始化/默认这些字段,但无法弄清楚如何操作。
模型 基本上,我的模型看起来像......
class Organisation(models.Model):
name = models.CharField(
verbose_name = 'Organisation Name',
max_length = 30
)
slug = models.SlugField (
verbose_name = "Slug",
allow_unicode = True,
unique=True,
blank=True,
null=True
)
user = models.ForeignKey(
User
)
class Factor (models.Model):
name = models.CharField(
verbose_name = 'Factor',
max_length = 30
)
class SupportingDocument(models.Model):
f = models.FileField(
upload_to ='supporting_document/'
)
factor = models.ForeignKey(
Factor,
blank = True,
null = True
)
organisation = models.ForeignKey(Organisation)
FORMS
class OrganisationFactorForm(forms.ModelForm):
class Meta:
model = Organisation
fields = ['user']
widgets = {
'user' : forms.HiddenInput(),
}
class SupportingDocumentInline(forms.ModelForm):
class Meta:
model = SupportingDocument
exclude = ['id', ]
widgets = {
'factor' : forms.HiddenInput(),
'organisation' : forms.HiddenInput(),
'f' : forms.FileInput(attrs={'class' : 'form-control'})
}
SupportingDocumentInlineFormSet = forms.inlineformset_factory(
Organisation,
SupportingDocument,
form=SupportingDocumentInline,
extra=1,
exclude = ['id'],
can_delete=True,
can_order=True)
VIEWS 我想默认因子记录,这样当我显示表单时,我可以做类似的事情
if self.request.POST:
form_count = int(self.request.POST['supportingdocument_set-TOTAL_FORMS'])
ctx['supporting_documents'] = SupportingDocumentInlineFormSet(self.request.POST, self.request.FILES, instance=self.get_object())
for x in range(form_count):
mutable = self.request.POST._mutable
self.request.POST._mutable = True
self.request.POST['supportingdocument_set-' + str(x) +'-factor'] = self.get_factor().id
self.request.POST._mutable = mutable
else : ctx['supporting_documents'] = SupportingDocumentInlineFormSet(instance=self.get_object(), queryset=SupportingDocument.objects.filter(factor=self.get_factor(), organisation=self.get_object()))
您注意到我目前正在使用self.request.POST._mutable = True
覆盖视图中的POST数据,这在我第一次加载组织/因子组合的文件时起作用,之后错误
在...的MultiValueDictKeyError " U' supportingdocument_set-0-ID'"
我真的可以在这里使用一些帮助。感谢