【问题标题】:How to capture values in checked checkboxes using Django如何使用 Django 捕获选中复选框中的值
【发布时间】: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


    【解决方案1】:

    您必须在 HTML 中创建一个表单来处理此 POST 请求。 然后在您的视图中使用if request.method == 'POST' 处理此问题,然后使用 getlist() 和更新函数。另外,我认为您需要在查询集中添加一个 for 循环,因为可能有多个产品。希望这会有所帮助!

    def inventory(request):
        if request.method == 'POST':
            products = request.POST.getlist('products')
            for product in products:
                a = Post.objects.filter(title=product).update(
                    quantity=F('quantity')-1
                )
        return redirect('blog-home')
    

    【讨论】:

    • 感谢您的回复。但是,问题是我的列表中什么也没有。它返回一个空列表,这意味着复选框中的值没有被捕获。
    猜你喜欢
    • 1970-01-01
    • 2011-05-27
    • 2015-06-13
    • 2011-01-25
    • 2011-08-15
    • 2014-08-04
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多