A
A
alexkomp2019-07-24 12:47:41
Django
alexkomp, 2019-07-24 12:47:41

How to fix django.db.utils.IntegrityError: NOT NULL constraint failed: index_cartbuy.cart_total error?

How to fix django.db.utils.IntegrityError: NOT NULL constraint failed: index_cartbuy.cart_total error?
The error appeared when I decided to make a basket for each user.
here is the cart model where the
models.py error is

class CartItem(models.Model):
    ware = models.ForeignKey('Ware', on_delete=models.CASCADE,)
    qty = models.PositiveIntegerField(default=1)
    item_total = models.DecimalField(max_digits=9, decimal_places=0)
    
    
    def __str__(self):
        return "CartBuy item for ware {0}".format(self.ware.title)
 

class CartBuy(models.Model):
    items_cart = models.ManyToManyField(CartItem, blank=True)
    cart_total = models.DecimalField(max_digits=9, decimal_places=0)
      
    
    def __str__(self):
        return str(self.id)

and view
views.py
def cart_view(request):
    try:
        cart_id = request.session['cart_id']
        cart = CartBuy.objects.get(id=cart_id)
        request.session['total'] = cart.items_cart.count()
    except:
        cart = CartBuy()
        cart.save()
        cart_id=cart.id
        request.session['cart_id'] = cart_id
        cart = CartBuy.objects.get(id=cart_id)
    context ={
        'cart': cart
    }
    return render(request, 'cart.html', context)
    
def add_to_cart_view(request, ware_pk):
    ware = Ware.objects.get(pk=ware_pk)
    new_item, _ = CartItem.objects.get_or_create(ware=ware, item_total=ware.prise)
    cart = CartBuy.objects.first()
    if new_item not in cart.items_cart.all():
        cart.items_cart.add(new_item)
        cart.save()
        return HttpResponseRedirect("/cart/")
    else:
        return HttpResponseRedirect("/")


def detail_ware(request, pk):
    try:
        cart_id = request.session['cart_id']
        cart = CartBuy.objects.get(id=cart_id)
        request.session['total'] = cart.items_cart.count()
    except:
        cart = CartBuy()
        cart.save()
        cart_id=cart.id
        request.session['cart_id'] = cart_id
        cart = CartBuy.objects.get(id=cart_id)
    ware = Ware.objects.get(pk=pk)
    context ={
        'ware': ware,
        'cart': cart
    }
    return render(request, 'detail_ware.html', context)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alternativshik, 2019-07-24
@alexkomp

It is written what is wrong...
cart_total cannot be NULL, and no values ​​are passed to it anywhere in the code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question