Ad

M2M Relation Ship : Can't Save To The Through Model

- 1 answer

i have a an order model which is in m2m relationship with a product model, when i create an order, and after checking my DB, i can see the order saved but not in the through model

models.py

from inventory.models import Product
from user.models import User

class Order(models.Model):
    product = models.ManyToManyField(Product, through='OrderItems' )
    vendeur = models.ForeignKey(User, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField()

class Customer(models.Model):
    full_name = models.CharField(max_length=60, verbose_name='full name')
    address = models.CharField(max_length=255)
    phone = models.CharField(max_length=20)
    city = models.CharField(max_length=30) 

class OrderItems(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    order = models.ForeignKey(Order,on_delete=models.CASCADE)    
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True)

views.py

@login_required
def add_order(request):
    if request.method == 'POST':
        form = NewOrderForm(request.POST)
        if form.is_valid():
            order = form.save(commit=False)
            order.vendeur = request.user
            order.save()        
            return redirect('dashboard-index', )
    else : 
        form = NewOrderForm()
    return render(request, 'dashboard/add_order.html', {'form': form})

forms.py

class NewOrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ('product','quantity')
Ad

Answer

if you use save(commit=False), Calling save_m2m() is required. because your form has a m2m field

refer to documentions

@login_required
    def add_order(request):
        if request.method == 'POST':
            form = NewOrderForm(request.POST)
            if form.is_valid():
                order = form.save(commit=False)
                order.vendeur = request.user
                order.save()
                form.save_m2m()        
                return redirect('dashboard-index', )
        else : 
            form = NewOrderForm()
        return render(request, 'dashboard/add_order.html', {'form': form})
Ad
source: stackoverflow.com
Ad