Last active
August 31, 2022 17:11
-
-
Save danilovmy/ea7c96415b406d3933ca29dfa18ac082 to your computer and use it in GitHub Desktop.
nested inline implementation in ModelForm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class MyForm(StackedInline.form): | |
| def __init__(self, *args, **kwargs): | |
| super(MyForm, self).__init__(*args, **kwargs) | |
| self.instance.form = self | |
| def is_valid(self): | |
| return super().is_valid() and self.nested.formset.is_valid() | |
| @cached_property | |
| def nested(self): | |
| modeladmin = ProductModelAdmin(self._meta.model, self.modeladmin.admin_site) | |
| # get formsets and instances for change/add view depending on the request | |
| formsets, instances = modeladmin._create_formsets(self.modeladmin.request, self.instance, change=self.instance.pk) | |
| # gets the inline from inline_formsets | |
| inline = modeladmin.get_inline_formsets(self.modeladmin.request, formsets[:1], instances[:1], self.instance)[0] | |
| # handles prefix | |
| inline.formset.prefix = f'{self.prefix}_{formsets[0].prefix}'.replace('-', '_') | |
| return inline |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment