I am making an offer creation module in Django, I have a product and a variant object, the product variant is connected with a many-to-many relationship. What I want to do is to save the products by selecting them while creating the offer, but at the same time to offer the option to choose the variants under the products.
The problem here is that the products and variants are not separate.
model.py
class offerProductVariant(models.Model):
offerProduct = models.ManyToManyField(product)
offerVariant = models.ManyToManyField(variant)
class offer(models.Model):
offerName = models.CharField(max_length=50)
offerCustomer = models.ForeignKey(customer,on_delete=models.CASCADE,null=True,blank=True)
offerCompany = models.ForeignKey(company,on_delete=models.CASCADE,blank=True)
offerDate = models.CharField(max_length=40)
offerProductVariantMany = models.ManyToManyField(offerProductVariant,blank=True)
views.py
def teklifsave(request):
if not request.user.is_authenticated:
return redirect('login')
if request.method == 'POST':
form = offerCreate(request.POST)
form2 = offerCreateProduct(request.POST)
if form.is_valid():
m = offer(
offerName = form.cleaned_data['offerName'],
offerCompany = form.cleaned_data['offerCompany'],
offerCustomer = form.cleaned_data['offerCustomer'],
offerDate = form.cleaned_data['offerDate']
)
m.save()
if form2.is_valid():
op = offerProductVariant()
op.save()
fproducts = form2.cleaned_data['offerProduct']
print(fproducts)
fvariants = form2.cleaned_data['offerVariant']
print(fvariants)
for fproduct in fproducts:
print(fproduct)
op.offerProduct.add(fproduct)
op.save()
for fvariant in fvariants:
print(fvariant)
op.offerVariant.add(fvariant)
op.save()
m.offerProductVariantMany.add(op)
return redirect('offer')
return redirect('offer')