Python 字段';产品标识';应为一个数字,但得到'&书信电报;django.db.models.query_utils.DeferredAttribute对象位于0x0000022D29594848>';
您好,正在尝试使用django保存数据并将其显示在我的购物车上。当我尝试将产品添加到购物车时,它会给我一个值错误。错误消息为:字段“Product_id”应为数字,但得到“”。以下是我的购物车文件源代码:Python 字段';产品标识';应为一个数字,但得到'&书信电报;django.db.models.query_utils.DeferredAttribute对象位于0x0000022D29594848>';,python,django,Python,Django,您好,正在尝试使用django保存数据并将其显示在我的购物车上。当我尝试将产品添加到购物车时,它会给我一个值错误。错误消息为:字段“Product_id”应为数字,但得到“”。以下是我的购物车文件源代码: from decimal import Decimal from django.conf import settings from store.models import Product class Cart(object): def __init__(self, request)
from decimal import Decimal
from django.conf import settings
from store.models import Product
class Cart(object):
def __init__(self, request):
"""
Initialize the cart.
"""
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
# save an empty cart in the session
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
def __iter__(self):
"""
Iterate over the items in the cart and get the products
from the database.
"""
product_ids = self.cart.keys()
# get the product objects and add them to the cart
products = Product.objects.filter(Product_id__in=product_ids)
cart = self.cart.copy()
for product in products:
cart[str(product.Product_id)]['product'] = product
for item in cart.values():
item['Price'] = Decimal(item['Price'])
item['total_price'] = item['Price'] * item['Quantity']
yield item
def __len__(self):
"""
Count all items in the cart.
"""
return sum(item['Quantity'] for item in self.cart.values())
def add(self, product, quantity=1, override_quantity=False):
"""
Add a product to the cart or update its quantity.
"""
product_id = str(product.Product_id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0,
'price': str(product.Price)}
if override_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] += quantity
self.save()
def save(self):
# mark the session as "modified" to make sure it gets saved
self.session.modified = True
def remove(self, product):
"""
Remove a product from the cart.
"""
product_id = str(product.Product_id)
if product_id in self.cart:
del self.cart[product_id]
self.save()
def clear(self):
# remove cart from session
del self.session[settings.CART_SESSION_ID]
self.save()
def get_total_price(self):
return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
我的模型:
from django.db import models
from django.urls import reverse
# Create your models here.
class Customer(models.Model):
Phone_number = models.IntegerField(primary_key=True)
First_name = models.CharField(max_length=50)
Last_name = models.CharField(max_length=50)
date_and_time_created = models.DateTimeField(auto_now=True)
class Category(models.Model):
Category_name = models.CharField(max_length=248, primary_key=True)
class Product(models.Model):
Product_id = models.IntegerField(primary_key=True)
Product_name = models.CharField(max_length=100)
Product_image = models.ImageField(null=True,blank=True)
Price = models.IntegerField()
discount_price = models.IntegerField(null=True)
Quantity = models.IntegerField()
description = models.TextField(null=True)
category = models.OneToOneField(Category, null=True, on_delete=models.CASCADE)
def get_absolute_url(self):
return reverse('store:prod',kwargs={'pk':self.Product_id})
class Order(models.Model):
order_id = models.IntegerField(primary_key=True)
billing_address = models.CharField(max_length=248)
Shipping_address = models.CharField(max_length=248)
date_and_time_ordered = models.DateTimeField(auto_now=True)
#add time of delivery
customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
product =models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
my views for the cart:
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from store.models import Product
from .cart import Cart
from .forms import CartAddProductForm
@require_POST
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, Product_id=product_id)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product,
quantity=cd['quantity'],
override_quantity=cd['override'])
return redirect('cartapp:cart_detail')
@require_POST
def cart_remove(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, Product_id=product_id)
cart.remove(product)
return redirect('cartapp:cart_detail')
def cart_detail(request):
cart = Cart(request)
for item in cart:
item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'],
'override': True})
return render(request, 'cartapp/detail.html', {'cart': cart})
我的购物车URL.py:
from django.urls import path, re_path
from cartapp import views
app_name = 'cartapp'
urlpatterns = [
path('', views.cart_detail, name='cart_detail'),
path('add/<product_id>/', views.cart_add, name='cart_add'),
path('remove/<int:product_id>/', views.cart_remove, name='cart_remove'),
]
希望我发布了正确的信息。我将感谢所有能得到的帮助。我清除了我的会话和cookie数据,它成功了。在卡添加(..,产品id)和卡删除(..产品id)中,您分配产品id=产品id。。。如何调用函数或为product\u id参数分配什么?共享您的
CartAddProductForm
@Razenstein。product\u id是模型中原始product\u id的字符串格式。它在cart.py文件夹中,我在cart@NKSM刚刚更新过
from django import forms
PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)]
class CartAddProductForm(forms.Form):
quantity = forms.TypedChoiceField(
choices=PRODUCT_QUANTITY_CHOICES,
coerce=int)
override = forms.BooleanField(required=False,
initial=False,
widget=forms.HiddenInput)