Python 如何使用提交按钮更新Django数据库?
我正在创建一个web应用程序,它将用作杂货店。我的设置方式是,客户可以访问网站,单击他们想要购买的项目,然后单击提交按钮购买这些项目。我遇到的问题是使用views.py函数获取所选产品的信息,并从数据库的数量中减去1Python 如何使用提交按钮更新Django数据库?,python,django,django-views,django-templates,django-database,Python,Django,Django Views,Django Templates,Django Database,我正在创建一个web应用程序,它将用作杂货店。我的设置方式是,客户可以访问网站,单击他们想要购买的项目,然后单击提交按钮购买这些项目。我遇到的问题是使用views.py函数获取所选产品的信息,并从数据库的数量中减去1 """models.py""" class Post(models.Model): title = models.CharField(max_length=100) Price = models.Decim
"""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')
类PostListView(ListView):
型号=员额
template_name='blog/home.html'#/_.html
上下文\对象\名称='posts'
def库存(请求):
products=request.POST.getlist('products')
对于产品中的产品:
a=Post.objects.get(title=product)
a、 数量=a.数量-1
a、 保存()
打印(产品)#此行不是必需的,但它将显示终端列表中的内容。
返回重定向('blog-home')
url.py
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
path('inventory', views.inventory, name='inventory'),
path('user/',UserPostListView.as_view(),name='user-posts'),
路径('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 %}
{%extends“blog/base.html”%}
{%block content%}
{posts%%中的post为%s}
{%如果post.quantity>0%}
{{post.category}
{{post.title}}
价格:${post.Price}
销售:${post.Sale}
存货盘点:{post.quantity}
{%else%}
{%endif%}
{%endfor%}
确认购买
{%endblock内容%}
我的目标是单击复选框,当客户单击home.html底部的按钮时,它会触发inventory函数从数量中减去“1”。当我说打印(产品)时,终端会给我所有打勾的帖子的标题。但是,它仍然没有进入数据库并从库存中减去1。(我解决了这个问题)使用
Post.objects.get('products[x]”)
没有意义,它期望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.shortcuts导入重定向
def库存(请求):
products=request.POST.getlist('products')
Post.objects.filter(pk\uu in=products).更新(
数量=F(‘数量’)-1
)
返回重定向(“配置文件”)
通过使用一个函数,可以批量减少所有Post
s,这比对每个Post对象进行两次数据库查询更有效
使用
HttpResponseRedirect(“{%url”配置文件“%}”)
也不会起作用。“{%url”配置文件“%}”
只是一个字符串,它不执行任何模板呈现。Django通常会返回HTTP 302响应,其中的链接为{%url'profile'%}
,但浏览器不理解{%url'profile'%}
,它只能与URI一起工作。您好,非常感谢您的响应。我更新了代码,这是我现在遇到的新错误receive@Yahya:您再次使用字符串而不是F
对象…@Yahya:您确定发出POST请求,并且请求.POST.getlist('products')
包含主键列表吗?@Yahya:但是
标记在哪里?将复选框包装在表单中,然后提交表单。看起来您使用了发出GET请求的
。您能否在视图中打印打印(产品)
,并查看产品
中包含的内容?@Yahya:您确定要发出POST请求吗?您通常可以在终端中看到请求。无论如何,您应该明确地将复选框包装在向视图发出POST请求的
中。