I have following structure.
models.py
class Parent(models.Model):
PROVIDER1 = "Provider1"
PROVIDER2= "Provider2"
PROVIDERS= (
(PROVIDER1, "Test Provider One"),
(PROVIDER2, "Test Provider Two"),
)
provider = models.CharField(
choices=PROVIDERS,
max_length=255,
default=PROVIDER1,
)
# Few more parent fields will be here
class Child(models.Model):
some_field= models.CharField(max_length=255)
# Few more fields will be here
parent = models.ForeignKey(
Parent, on_delete=models.CASCADE
)
admin.py
class ChildFormset(BaseInlineFormSet):
def clean(self):
super().clean()
for form in self.forms:
if not form.is_valid():
return # errors exist, so return
class ChildInline(admin.StackedInline):
model = Child
formset = ChildFormset
extra = 1
min_num = 1
validate_min = True
max_num = 1
can_delete = False
@admin.register(Parent)
class Parent(admin.ModelAdmin):
form = ParentForm
inlines = [
ChildInline,
]
forms.py
class ParentForm(forms.ModelForm):
class Meta:
model = Parent
fields = "__all__"
def clean(self):
cleaned_data = super().clean()
# How to access Child model's fields values here to validate them?
class Media:
# Custom JS to show/hide provider specific fields/divs
js = ("js/mycustom.js",)
Requirement:
When admin user choose Provider 1 in the Parent I would like to do following
- Display Child Model's fields (Inline).
- Validate Child model's fields on submit.
I was able to use custom JavaScript for first requirement (hiding and showing fields).
But for second requirement I am not able to get the Child model's fields into Parent Form's clean()
method or Parent model's chosen provider
into ChildFormset's clean()
method.
The current validation works irrespective of the option chosen by user for Provider.