0

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.

Antoine Pinsard
  • 33,148
  • 8
  • 67
  • 87
  • possible duplicate of [How do I filter ForeignKey choices in a Django ModelForm?](http://stackoverflow.com/questions/291945/how-do-i-filter-foreignkey-choices-in-a-django-modelform) – Burhan Khalid Aug 29 '12 at 11:09
  • from what I understood, this is more about filtering choices, which is not what I want to do. – Antoine Pinsard Aug 29 '12 at 11:27

3 Answers3

1

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
Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100
0

If you want to show proper text for 'B' in choice field, in your model B add __unicode__ method and return string using fields of B,

eg.

class B(models.Model):
    a = models.IntegerField(...)
    b = models.CharField(...)
    c = models.BooleanField(...)
    def __unicode__(self):
         return u''+str(self.a) + ':' + self.b
Rohan
  • 52,392
  • 12
  • 90
  • 87
0

inlineformset_factory accepts form argument, which is a modelform class for your "B" objects. So, defining a form class with fields = ('a', 'b') in Meta and passing it to the function should help.

uruz
  • 1