簡體   English   中英

如何使用提交按鈕更新我的 Django 數據庫?

[英]How to update my Django database with a submit button?

我正在創建一個用作雜貨店的 web 應用程序。 我設置它的方式是讓客戶可以進入網站,點擊他們想要購買的商品,然后點擊提交按鈕購買這些商品。 我遇到的問題是有一個views.py function 來獲取選擇了哪些產品的信息並從數據庫的數量中減去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})

視圖.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')

網址.py

    path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
    path('inventory', views.inventory, name='inventory'),

主頁.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 底部的按鈕時,它會觸發庫存 function 從數量中減去“1”。 當我說打印(產品)時,終端會給我所有選中的帖子的標題。 但是,它仍然沒有進入數據庫並從庫存中減去 1。 (我解決了)

使用Post.objects.get('products[x]')沒有意義,.get(…)方法 [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')

通過使用.update(…) [Django-doc] ,您可以批量減少所有Post ,這比每個Post object 進行兩次數據庫查詢更有效。

使用HttpResponseRedirect("{% url 'profile'%}")也不起作用。 "{% url 'profile'%}"只是一個字符串,它不執行任何模板渲染。 Django will normally return a HTTP 302 response, with {% url 'profile' %} as link to go to, but the browser does not understand {% url 'profile' %} , it can only work with a URI.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM