Search code examples
djangoformsdjango-formsdjango-formwizard

Django form and many2many.through field


I'm building a wizard (using Django Formtools) that would allow one to order one or several items, with the possibility for each selected item to specify the quantity desired.

I'd like to avoid the classical cart system and make the purchase as simple as possible. My navigation proposal is to have only 3 pages/steps:

  1. the first page show a form with all the available items. those items can be selected and visitors can specify a quantity.
  2. the second page makes a summary of the order and visitors are asked to fill their details
  3. the last page confirms the order

I'm having troubles creating the form for the first step and I'm looking for help to find a middleground between the two options I tried.

My Django models look like this (simplified for the demonstration):

class Item(models.Model):                                                                                                                   
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=5, decimal_places=2)

class Order(TransactionBase):
    items = models.ManyToManyField(Item, through='OrderedItem')

class OrderedItem(models.Model):
    order = models.ForeignKey(Order)
    item = models.ForeignKey(Item)
    quantity = models.PositiveSmallIntegerField()

Using the following ModelForm I'm able to list all the available Items:

class OrderSelectionForm(forms.ModelForm):
    class Meta:
        model = Order                                                                                                                            
        fields = ('items',)
        widgets = {
            'items': forms.CheckboxSelectMultiple(),
        }

But it doesn't allow for specifing the quantity...

Using the following code, I'm able to create a form that lets one specifing the quantity:

inlineformset_factory(Order, Order.items.through)

But instead of showing a flat list of all the available items, it shows me 3 sets with a dropdown list to select the wanted item.

How would you combine the two approches to get a form that list all the available items, allowing one to specify the quantity?

Thanks a lot.


Solution

  • [EDIT]: Deleted previous answer as it was a copy error.

    At this stage you're not handling an order. You're providing a catalog with products that when submitted generate an order. So base your form off of Items, give the checkbox and quantity input a name that can be linked to the item (incorporate the item's primary key) and then generate the order upon submission.