Search code examples
djangodjango-formsinline-formset

django forms - Access fields of a foreign key


I'd like to create a modelform from a model A which has a foreign key to a model B :

class A(models.Model):
    a = models.CharField(...)
    b = models.ForeignKey(B)
    c = models.CharField(...)

class B(models.Model):
    a = models.IntegerField(...)
    b = models.CharField(...)
    c = models.BooleanField(...)

So I did this :

class AForm(forms.ModelForm):
    class Meta:
        model = A

But I only want some fields :

class AForm(forms.ModelForm):
    class Meta:
        model = A
        fields = ('a', 'b')

The problem is here, I don't want b to be a list of B objects, but I want the fields B.a and B.c (for instance). I tried "fields = ('a', 'b.a', 'b.c')" and "fields = ('a', 'b_a', b_c')" but fruitlessly.

So I came to inline formsets, but I didn't see anything to restrict the set of fields of the inline.

What should I do ? Thanks.


Solution

  • You can restrict the inline fields like this (ofcourse you still need the form to validate, you could use javascript or default values to set gaps)

    class MyModelInline(admin.TabularInline):
        model = MyModel
        fields = ["x", "y", "z"]
    
        #fk_name = "..."
        #max_num = 1
        #extra = 0