【发布时间】:2020-12-11 11:04:21
【问题描述】:
我正在创建一个用作杂货店的 Web 应用程序。我设置它的方式是让客户可以进入网站,单击他们想要购买的商品,然后单击提交按钮购买这些商品。我遇到的问题是有一个views.py 函数来获取选择了哪些产品的信息并从数据库的数量中减去1。当我在 views.py 中说 print(products) 时,它会在我的终端中返回“[]”。这意味着我选中的复选框中的值没有被捕获。谁能帮我解决这个问题?
"""models.py"""
class Post(models.Model):
title = models.CharField(max_length=100)
Price = models.DecimalField(max_digits=4, decimal_places=2,default=1)
Sale = models.DecimalField(max_digits=4, decimal_places=2,default=1)
quantity = models.IntegerField(default=1)
author = models.ForeignKey(User, on_delete=models.CASCADE)
category = TreeForeignKey('Category',null=True,blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
views.py
class PostListView(ListView):
model = Post
template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
def inventory(request):
products = request.POST.getlist('products')
a = Post.objects.filter(title=products).update(
quantity=F('quantity')-1
)
return redirect('blog-home')
urls.py
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
path('inventory', views.inventory, name='inventory'),
home.html
{% extends "blog/base.html" %}
{% block content %}
{% for post in posts %}
{% if post.quantity > 0 %}
<input type="checkbox" name="products" id="product_{{ post.id }}" value="{{ post.id }}">
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.category }}</a>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content"> Price: ${{ post.Price }}</p>
<p class="article-content"> Sale: ${{ post.Sale }}</p>
Inventory count: {{ post.quantity }}
</input>
</div>
</article>
{% else %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.category }}</a>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content"> Price: ${{ post.Price }}</p>
<p class="article-content"> Sale: ${{ post.Sale }}</p>
Inventory count: {{ post.quantity }}
<p>Out Of Stock!</p>
</div>
</article>
{% endif %}
{% endfor %}
<a href="{% url 'inventory' %}"><button type="submit" name="Purchase" >Confirm Purchase</button></a>
{% endblock content %}
我的目标是点击复选框,当客户点击home.html底部的按钮时,它会触发库存功能从数量中减去“1”。
【问题讨论】:
标签: python django django-views django-forms django-templates