如何使用提交按钮更新我的 Django 数据库?

How to update my Django database with a submit button?

我正在创建一个用作杂货店的 Web 应用程序。我的设置方式是让客户可以进入网站,点击他们想要购买的商品,然后点击提交按钮购买这些商品。我 运行 遇到的问题是有一个 views.py 函数来获取选择了哪些产品的信息,并从数据库的数量中减去 1。

"""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')
    for product in products:
        a = Post.objects.get(title=product)
        a.quantity = a.quantity -1
        a.save()
    print(products) # This line isn't necessary but it will show what is in your list from the terminal.
    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 %}
    <form action="{% url 'inventory' %}" method="POST" id="menuForm">
      {% for post in posts %}
        {% if post.quantity > 0 %}
            <article class="media content-section">
              <div class="media-body">
                <div class="article-metadata">
                  <a class="mr-2">{{ post.category }}</a>
                </div>
                <h2><a class="article-title" >{{ post.title }}</a></h2>
                <p class="article-content"> Price: ${{ post.Price }}</p>
                <p class="article-content"> Sale: ${{ post.Sale }}</p>
                <input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }}
              </input>
              </div>
            </article>
        {% else %}
        {% endif %}
      {% endfor %}
      <button type="submit" form="menuForm">Confirm Purchase</button>
    </form>
{% endblock content %}

我的目标是点击复选框,当客户点击home.html底部的按钮时,它会触发库存功能从数量中减去“1”。当我说 print(products) 时,终端会给我所有 check-marked 的帖子的标题。但是,它仍然没有进入数据库并从库存中减去 1。 (我解决了)

使用 Post.objects.get('products[x]') 没有意义,.get(…) method [Django-doc] 期望 Q 对象作为位置参数,或 named 参数,例如:

from django.shortcuts import redirect

def inventory(request):
    <b>products =</b> request.POST.getlist('products')
    Post.objects.filter(<b>pk__in=products</b>).update(
        <b>quantity=F('quantity')-1</b>
    )
    return redirect('profile')

通过使用 .update(…) [Django-doc],您可以减少 bulk 中的所有 Post,这比进行两次数据库查询 per Post 对象.

使用HttpResponseRedirect("{% url 'profile'%}") 也不行。 "{% url 'profile'%}" 只是一个字符串,它不执行任何模板渲染。 Django 通常会 return 一个 HTTP 302 响应,用 {% url 'profile' %} 作为 link 去,但是浏览器不理解 {% url 'profile' %} , 它只能与 URI 一起使用。