Допустим, мы хотим профильтровать опции в инлайн форме в зависимости от инстанса объекта. И все это в админке. Для этого сначала можно пробросить его в keyword arguments формы, а затем получить оттуда

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class PageNodeAttachmentInline(admin.TabularInline):
model = PageNodeAttachment
form = PageNodeAttachmentForm
formset = PageNodeAttachmentInlineFormSet
extra = 2
class PageNodeAttachmentForm(forms.ModelForm):
node_id = forms.ChoiceField()
class Meta:
model = PageNodeAttachment
fields = ('node_id', 'page_type')
def __init__(self, *args, **kwargs):
attachment_page = kwargs.pop('attachment_page', None)
super(PageNodeAttachmentForm, self).__init__(*args, **kwargs)
self.fields['node_id'].choices = get_nodes_for_page(attachment_page)
class PageNodeAttachmentInlineFormSet(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
super(PageNodeAttachmentInlineFormSet, self).__init__(*args, **kwargs)
attachment_page = kwargs.get('instance', None)
if attachment_page:
self.form_kwargs['attachment_page'] = attachment_page