I am working on my first django-project and I am trying to build an e-commerce website from scratch. I tried to write a logical flow for adding an item to my chart but somewhere I'm mistaken. It continuously raises an error that I do now know how to handle.
In models.py I created the model for an item that will be added to the chart and it'll be displayed on the chart.html page.
models.py
class UserItem(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
price = models.FloatField(blank=True, null=True)
img = models.ImageField(upload_to='gallery', blank=True, null=True)
quantity = models.IntegerField(default=1)
prod_id = models.ForeignKey(to=ComputerScienceProducts, on_delete=models.CASCADE, blank=True, null=True)
def add_item_to_cart(self, prod_id):
prod = ComputerScienceProducts.objects.get(pk=prod_id)
try:
existing_prod = UserItem.objects.get(prod)
existing_prod.quantity += 1
existing_prod.save()
except:
new_prod = UserItem.objects.create(name = prod.name, price=prod.price,
img=prod.img)
new_prod.save()
In views.py, the logic I tried to implement in coding lines is: If the user clicks the button "add to chart", will be sent through a GET method the pk of the product he wants to add on his or her chart. From that point, I look for the product that has that PK in the database. Then I check whether the product is already in the cart and if so, I just increase the quantity by 1, and if not, I create a new object that I store in the database, which then will be displayed on its corresponding template. views.py
def add_to_cart(request):
if request.method == 'GET':
if len(request.GET.keys()) > 1:
Idd = list(request.GET.keys())[1]
prod = ComputerScienceProducts.objects.filter(pk=Idd)
try:
cart = UserItem.objects.get(prod_id=list(prod)[0].id)
cart.quantity +=1
cart.save()
except:
cart = UserItem.objects.create(
name=list(prod)[0].name,
price = list(prod)[0].price,
img = list(prod)[0].img,
prod_id = list(prod)[0].id
)
cart.save()
cart.add_item_to_cart(Idd)
After executing the code, the following error is being raised:
Traceback (most recent call last):
File "C:\Users\User\new-project\FinalProject\cPhilosophy\mainpages\views.py", line 77, in add_to_cart
cart = UserItem.objects.get(prod_id=list(prod)[0].id)
File "C:\Users\User\new-project\FinalProject\cPhilosophy\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\User\new-project\FinalProject\cPhilosophy\venv\lib\site-packages\django\db\models\query.py", line 429, in get
raise self.model.DoesNotExist(
mainpages.models.UserItem.DoesNotExist: UserItem matching query does not exist.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\User\new-project\FinalProject\cPhilosophy\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\User\new-project\FinalProject\cPhilosophy\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\User\new-project\FinalProject\cPhilosophy\mainpages\views.py", line 81, in add_to_cart
cart = UserItem.objects.create(
File "C:\Users\User\new-project\FinalProject\cPhilosophy\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\User\new-project\FinalProject\cPhilosophy\venv\lib\site-packages\django\db\models\query.py", line 445, in create
obj = self.model(**kwargs)
File "C:\Users\User\new-project\FinalProject\cPhilosophy\venv\lib\site-packages\django\db\models\base.py", line 483, in __init__
_setattr(self, field.name, rel_obj)
File "C:\Users\User\new-project\FinalProject\cPhilosophy\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 215, in __set__
raise ValueError(
ValueError: Cannot assign "2": "UserItem.prod_id" must be a "ComputerScienceProducts" instance.
I have to mention that I override the User model as follows:
class CustomUser(AbstractUser):
street = models.CharField(max_length=50, blank=True, null=True)
number = models.IntegerField(blank=True, null=True)
city = models.CharField(max_length=50, blank=True, null=True)
country = models.CharField(max_length=50, blank=True, null=True)
zip_code = models.IntegerField(blank=True, null=True)
phone_number = models.CharField(max_length=20)
profile_image = models.ImageField(upload_to='gallery',blank=True, null=True, default="profiledef.png")
def __str__(self):
return self.username
Read more here: https://stackoverflow.com/questions/66322740/adding-an-item-to-a-chart-in-django-attribute-error
Content Attribution
This content was originally published by tudor.il at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.