【发布时间】:2020-12-08 14:28:29
【问题描述】:
我正在创建一个用作杂货店的 Web 应用程序。我希望它以某种方式工作,以便当客户单击复选框并单击提交时,数据库会将库存数量减去 1。我无法从复选框中捕获信息,然后使用它来减去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'
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
fields = ['title', 'Price', 'Sale', 'quantity', 'category',]
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
Post = self.get_object()
#editor = self.get_object()
if self.request.user == Post.author:
return True
return False
home.html
{% extends "blog/base.html" %}
{% block content %}
{% for post in posts %}
{% if post.quantity > 0 %}
<input type="checkbox" name="product[]" id=" {{ 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 %}
<button type="submit" name="Purchase">Confirm Purchase</button>
{% endblock content %}
urls.py
path('', PostListView.as_view(), name='blog-home'),
我附上了一张主页外观的图片作为参考。任何帮助表示赞赏。谢谢。
【问题讨论】:
标签: python django checkbox django-views django-templates