【问题标题】:Suggest a way to populate database on button click建议一种在按钮单击时填充数据库的方法
【发布时间】:2019-06-10 17:54:49
【问题描述】:

我是一名新手 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)

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)

【问题讨论】:

    标签: python django django-templates django-views


    【解决方案1】:

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

    【讨论】:

    • 谢谢,但是我现在如何更新我的 urls.py,因为在按钮单击时检测到 url 模式匹配错误。我的 urls.py 是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)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多