简体   繁体   中英

IntegrityError at /add_to_cart/ NOT NULL constraint failed:

I have a view which adds the items to the cart, but when I try to add the items to the cart Item model rising an error NOT NULL constraint failed: cart_item.product_id

I have created a model Item to capture the selected items

Here is my models.py

from django.db import models
from django.contrib.auth.models import User
# Create your models here.


class Product(models.Model):
    product_title = models.CharField(null=True, blank=True,max_length=200)
    product_price = models.IntegerField(null=True, blank=True,)
    product_image = models.ImageField(upload_to='cart/products/', null=True, blank=True)

    def __str__(self):
        return self.product_title

class Cart_Bucket(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    create_date = models.DateTimeField(null=True, blank=True,verbose_name='create_date', auto_now=True)
    checked_out = models.BooleanField(default=False, verbose_name='checked_out')

    def __unicode__(self):
        return unicode(self.create_date)

class Item(models.Model):
    cart = models.ForeignKey(Cart_Bucket, verbose_name='cart', on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(verbose_name='quantity')
    product = models.ForeignKey(Product, verbose_name='product', related_name='product', on_delete=models.CASCADE)

    def __str__(self):
        return u'%d units' % (self.quantity)

Views.py

def add_to_cart(request):
    user = request.user
    if not user.is_authenticated:
        chars = string.ascii_uppercase + string.digits
        user_name = ''.join(random.choice(chars) for _ in range(9))
        password = '1234567a'
        user = User.objects.create(username=user_name, first_name='guest', last_name='guest', email='guest@gmail.com', is_active=True, is_staff=True)
        user.set_password(password)
        user.save()
        user = authenticate(username=user_name, password=password)
        if user:
            login(request, user)

    product_id = request.GET.get('product_id')
    cart = Cart_Bucket.objects.filter(checked_out=False, user=user)
    cart = cart[0] if cart else ''
    if not cart:
        cart = Cart_Bucket.objects.create(user=user)

    Item.objects.create(cart=cart, product_id=product_id, quantity=1)
    print(Item.objects.all)
    return render(request, 'products/products.html')

my products.html

{% extends 'home/base.html' %}

{% block body %}

<div class="row">
        {% for products in product %}
        <div class="col-md-6 col-centered">

                <img src="{{ products.product_image.url }}" style="width: 30%;display:block;margin:0 auto;">
                <div class="row">
                    <div class="col-md-2"></div>
                    <div class="col-md-6">
                        <br>
                        <p>{{ products.product_title }}  Price : $ {{ products.product_price }} </p>

                    </div>
                    <div class="col-md-6"></div>
                    <div class="col-md-4">
                        <a href="{% url 'add_to_cart' %}?products_id={{ products.id }}" class="btn btn-success" role="button">Add to Cart</a>
                    </div>
                    <div class="col-md-2"></div>
                </div>    
                <hr>
        </div>

        {% endfor %}
</div>
{% endblock %}

I want to see the add_to_cart items on the cart page

I think that raises the problem because Item.objects.create() tries to save the model to the database first, before parsing all arguments. Based on Django documentation, .save() method has some advantages over create() method. This problem should be resolved if you change your code like:

newItem = Item()
newItem.cart = cart
newItem.product_id = product_id
newItem.quantity = 1
newItem.save()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM