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

2024-04-20 06:48:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个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')

url.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底部的按钮时,它会触发inventory函数从数量中减去“1”。当我说打印(产品)时,终端会给我所有打勾的帖子的标题。但是,它仍然没有进入数据库并从库存中减去1。(我解决了)


Tags: namepyselfformhometitlemodelshtml
1条回答
网友
1楼 · 发布于 2024-04-20 06:48:57

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

from django.shortcuts import redirect

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

通过使用^{} [Django-doc]可以减少批量中的所有Post,这比对每个Post对象进行两次数据库查询更有效

使用HttpResponseRedirect("{% url 'profile'%}")也不起作用。"{% url 'profile'%}"只是一个字符串,它不执行任何模板呈现。Django通常会返回一个HTTP 302响应,其中{% url 'profile' %}作为要转到的链接,但浏览器不理解{% url 'profile' %},它只能使用URI

相关问题 更多 >