我试图理解的Django源代码中有两个模型DfHeaderInfo
和DfInpValidation
。这两个模型都具有另一个模型DfInpAdmin
的外键。这两种模型都以tabularinline的形式出现在主要的DfInpAdmin
形式中。但是在admin.py
中,我可以看到DfHeaderInfo
也有DfHeaderInfoInline
,DfHeaderInfoForm
和相应的表单集DfHeaderInfoFormSet
。但是对于DfInpValidation
,没有相应的表单集。只有DfInpValidationForm
和DfInpValidationInline
。
我无法弄清楚使用formset对DfHeaderInfo
的要求或特殊功能是什么?我可以用类似的方式从DfInpAdmin
更新两个模型。那么,什么是额外的福利表单集?
class DfHeaderInfoFormSet(BaseInlineFormSet):
def get_form_kwargs(self, index):
kwargs = super().get_form_kwargs(index)
kwargs['parent_object'] = self.instance
return kwargs
class DfHeaderInfoForm(forms.ModelForm):
class Meta:
model = DfHeaderInfo
fields = "__all__"
def __init__(self, *args, parent_object, **kwargs):
try:
self.parent_object = parent_object
print(self.parent_object)
self.df_inp_fk = self.parent_object.df_inp_pk
super(DfHeaderInfoForm, self).__init__(*args, **kwargs)
self.fields['alias'] = forms.CharField(
widget=forms.TextInput(attrs={'size': 30}),
label="Alias Name",
help_text='Alias of XPATH/Header)',
required=False)
self.fields['expression'] = forms.CharField(
widget=forms.TextInput(attrs={'size': 30}),
label="Expression",
help_text='Expression for XPATH/Header)',
required=False)
except ObjectDoesNotExist as e:
super(DfHeaderInfoForm, self).__init__(*args, **kwargs)
def clean(self):
cleaned_data = self.cleaned_data
alias = self.cleaned_data.get("alias")
if not alias:
raise forms.ValidationError("Alias cannot be Blank")
return cleaned_data
class DfHeaderInfoInline(PaginationInline):
model = DfHeaderInfo
extra = 0
formset = DfHeaderInfoFormSet
form = DfHeaderInfoForm
fk_name = 'df_inp_fk'
list_display = ('alias', 'expression',)
class DfInpValidationForm(forms.ModelForm):
class Meta:
model = DfInpValidation
fields = "__all__"
widgets = {
'validation_name':
forms.TextInput(attrs={'size': 20}),
'inp_param':
forms.TextInput(attrs={'size': 50})
}
def __init__(self, *args, **kwargs):
super(DfInpValidationForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['df_validation_fk'].queryset = DfValidation.objects.filter(validation_type__icontains='DFINPCHECK')
class DfInpValidationInline(admin.TabularInline):
model = DfInpValidation
extra = 0
form = DfInpValidationForm
fk_name = 'df_inp_fk'
list_display = ('df_validation_fk', 'validation_name','inp_param')
fields = (
'df_validation_fk',
'validation_name',
'inp_param', )