Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

M2M relation ship : Can't save to the through model

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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')

>Solution :

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})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading