I have a model in my project which is rendered as an inline of an other model.
The inline model has a property (not a field) that I need in my template for a particular check, but I don't want it shown as a field. I can't find a way to make such field rendered as hidden, so that the entire <TD>
disappears.
I've both tried with Meta
class:
class MyFormset(forms.models.BaseInlineFormSet):
class Meta:
widgets = {
'to_be_hidden_property': forms.HiddenField,
}
and with add_fields
method:
class MyFormset(forms.models.BaseInlineFormSet):
def add_fields(self, form, index):
super(MyFormset, self).add_fields(form, index)
form.fields["to_be_hidden_property"].widget = forms.HiddenInput()
but both failed. First attempt simply gets ignored, while second one leads to a KeyError exception (field doesn't exist).
I'm open to suggestions, as I'd really hate to have to hide it via JS.
EDIT (adding admin.TabularInline
code):
class AssegnamentoCommessaConsulenzaInline(admin.TabularInline):
formset = AssegnamentoCommessaConsulenzaFormset
model = AssegnamentoCommessaConsulenza
template = 'admin/commessa/edit_inline/assegnamentocommessaconsulenza_tabular.html'
extra = 0
readonly_fields = (
'get_fase',
'get_configuration_link_inline',
'numero_erogazioni_effettuate', # Field to hide
)
class Media:
js = ('useless things', )
css = {'all': ('even less useful things', )}
EDIT (to explain what I've tried after @Alasdair's suggestion):
from django.forms.models import inlineformset_factory
class MyFormAbstract(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyFormAbstract, self).__init__(*args, **kwargs)
self.fields['to_be_hidden_property'] = forms.CharField(
widget=forms.HiddenInput(),
initial=self.instance.to_be_hidden_property
)
class Meta:
model = MyModel
fields = '__all__'
MyFormset = inlineformset_factory(
MyMainModel,
MyInlineModel,
form=MyFormAbstract
)
This whole thing seems to get silently ignored. There are no errors, but the property is still there.
答案 0 :(得分:0)
您可能会发现customize the model form更容易,而不是继承BaseInlineFormSet
。
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['property_field'] = forms.CharField(widget=forms.HiddenInput(), initial=self.instance.property_field)
MyInlineFormset = inlineformset_factory(MyMainModel, MyModel, form=MyForm)
请注意,所有这一切都是将隐藏字段添加到表单中,您必须添加所需的任何其他处理。