0

我有一个使用自定义表单类的管理员内联。如何从该表单类的函数中访问父实例(外键)?

相关代码如下:

模型.py:

class Bar(models.Model):
    name = models.CharField(max_length=50)

class Foo(models.Model):
    name = models.CharField(max_length=50)
    bar = models.ForeignKey(Bar, null=True, blank=True, related_name="foos")

管理员.py:

class FooInlineAdmin(admin.TabularInline):
    model = Foo
    form = AdminFooForm
    max_num = 3

class Bar(admin.ModelAdmin):
    inlines = [FooInlineAdmin]

表格.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

我知道一旦有一个实际实例,我就可以使用instance.bar. 但是,这只有在确实有记录时才有效,对吗?因此,如果我使用此表单创建记录,则实例将为无。

4

1 回答 1

1

试试这个:

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

希望对您有所帮助。

于 2011-07-29T02:57:12.197 回答