I have an admin inline that uses a custom form class. How can I access the parent instance (foreign key) from within the functions of that form class?
Relevant code below:
models.py:
class Bar(models.Model):
name = models.CharField(max_length=50)
class Foo(models.Model):
name = models.CharField(max_length=50)
bar = mode开发者_JAVA技巧ls.ForeignKey(Bar, null=True, blank=True, related_name="foos")
admin.py:
class FooInlineAdmin(admin.TabularInline):
model = Foo
form = AdminFooForm
max_num = 3
class Bar(admin.ModelAdmin):
inlines = [FooInlineAdmin]
forms.py:
class AdminFooForm(forms.ModelForm):
class Meta:
model = Foo
def clean(self):
data = self.cleaned_data
mybar = self.get_foreign_key_somehow() # this is the line I'm interested in
I know that once there is an actual instance, I can access it using instance.bar
. However, that only works once there's acually a record, right? So if I am using this form to create a record, instance is going to be None.
Give this a try:
class FooInlineFormset(forms.models.BaseInlineFormSet):
def clean(self):
for form in self.forms:
try:
if form.cleaned_data:
delete = form.cleaned_data.get('DELETE')
if not delete:
bar = form.cleaned_data.get('bar', None)
except AttributeError:
pass
class FooInlineAdmin(admin.TabularInline):
model = Foo
formset = FooInlineFormset
form = AdminFooForm
max_num = 3
Hope that helps you out.
精彩评论