python - 建议一种在单击按钮时填充数据库的方法

标签 python django django-templates django-views

我是一名 Django 程序员新手,正在尝试构建一个基本的 e-commerce website 。我想通过按“添加到购物车”按钮将所选项目添加到数据库并加载相同的主页。 单击此按钮时出现 错误: MultiValueDictKeyError at/ '添加购物车' 如果需要,请建议任何其他好的方法

我的按钮模板是:

<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})

模型.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)

url.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)

最佳答案

您应该使用action="post",检查方法是否等于"POST",并从request.POST获取数据。

关于python - 建议一种在单击按钮时填充数据库的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56531268/

相关文章:

python - 按键(整数)对字典进行有效排序,返回排序的值列表

python - 尝试使其在 Django 上运行 Regex/url/views

python - django/celery - celery 状态 : Error: No nodes replied within time constraint

python - 如何从 django 模板发布到 django 中的 View ?

django - 在 Django 模板中渲染字典

python - 从一个数组中删除另一个数组中的所有数字

python - 如何为 MS Windows PACKAGE_ID 和 PACKAGE_INFO 结构创建 Python ctypes 结构?

python - 如何在python中缩短浮点结果

django - 如何在Elasticsearch中运行查询和过滤器的组合?

python - Django 模板标签返回 True 或 False