0

Assuming I have :

class Product(models.Model):
    [...]

class Basket(models.Model):
    content = models.ManyToManyField(Product, through="ProductQuantity")

class ProductQuantity(models.Model):
    basket = models.ForeignKey(Basket)
    product = models.ForeignKey(Product)
    quantity = models.IntegerField(default=0)

How could I render a ModelForm for the Basket Model with a field for each ProductQuantity of a Basket, just to be able to modify its quantity attribute?

Is there a widget I could use for this?

If I was able to do such thing with such a ModelForm, could I use this ModelForm in an admin.ModelAdmin as an alternative form attribute to have the same behaviour in the admin interface?

Edit :

@MuhammadTahir marked this post as possible duplicate of this post.

It indeed helped me to understand better, but I'm still stuck : I can't render the fields I want to render.

Here is my code so far :

models.py

Same as above.

forms.py

ProductQuantityFormSet = inlineformset_factory(Product,
                                               basket.content.through,
                                               fields=("quantity",))

admin.py

class ProductQuantityInline(admin.StackedInline):
    model = ProductQuantity
    formset = ProductQuantityFormSet()

class BasketAdmin(admin.ModelAdmin):
    inline = [ProductQuantityInline,]
Community
  • 1
  • 1
vmonteco
  • 14,136
  • 15
  • 55
  • 86
  • 1
    Possible duplicate of [Accessing Many to Many "through" relation fields in Formsets](http://stackoverflow.com/questions/11021242/accessing-many-to-many-through-relation-fields-in-formsets) – Muhammad Tahir Apr 13 '16 at 16:13

1 Answers1

0

Someone on IRC found the problem :

inlineinlines in the admin.ModelAdmin. And I don't even need the inlineformset_factory().

So here is the final code :

models.py

class Product(models.Model):
    [...]

class Basket(models.Model):
    content = models.ManyToManyField(Product, through="ProductQuantity")

class ProductQuantity(models.Model):
    basket = models.ForeignKey(Basket)
    product = models.ForeignKey(Product)
    quantity = models.IntegerField(default=0)

admin.py

class ProductQuantityInline(admin.StackedInline):
    model = ProductQuantity
    fields = ["quantity",]

class BasketAdmin(admin.ModelAdmin):
    inlines = [ProductQuantityInline,]

I hope this could help somebody else. :)

vmonteco
  • 14,136
  • 15
  • 55
  • 86