我是Django的新手程序员,正在尝试构建基本的e-commerce website。我想通过按“添加到购物车”按钮将所选项目添加到数据库并加载相同的主页。 点击此按钮时出现错误 错误: 位于/的MultiValueDictKeyError 'add_cart' 如有需要,请提出其他任何好的方法
我的按钮模板是:
<form action="get">
<button
type="submit"
class="button1"
value="{{ product.id }}"
name="add_cart">Add to Cart
</button>
</form>
views.py:
def home(request):
products = Products.objects
product_id=None
if request.method == "POST":
product_id = request.POST['add_cart']
if product_id:
product = Products.objects.get(id=int(product_id))
if product:
product.c_title =product.title
product.c_description = product.description
product.c_price = product.price
product.customer = request.user
product.save()
return redirect(request, 'products/home.html',{'products': products})
return render(request, 'products/home.html',{'products': products})
models.py 在这里,我在商品中使用了“ c_”前缀来存储该用户的购物车商品
class Products(models.Model):
title = models.CharField(max_length = 100)
body = models.TextField()
description = models.TextField()
price = models.IntegerField()
image = models.ImageField(upload_to = 'images/')
customer = models.ForeignKey(User, on_delete = models.CASCADE)
total_items = models.IntegerField(default = 1)
icon = models.ImageField(upload_to = 'images/')
c_title = models.CharField(max_length = 100)
c_description = models.TextField()
c_price = models.IntegerField()
c_total_items = models.IntegerField(default = 1)
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from products import views as product_views
urlpatterns =[
path('admin/', admin.site.urls),
# path('', include('products.urls')),
path('', product_views.home,name='home'),
path('accounts/', include('accounts.urls')),
path('cart/', include('cart.urls'))
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
答案 0 :(得分:0)
您应该使用action="post"
,检查等于"POST"
的方法,然后从request.POST
获取数据。