簡體   English   中英

從 POST 請求中打印數據時,request.POST.get() 在 Django App 中返回 None

[英]When printing out data from a POST request, request.POST.get() returns None in Django App

我正在構建一個電子商務網絡應用程序。 我正在嘗試使用一些庫存 html 產品卡代碼構建“添加到購物車”功能,並將事件偵聽器添加到“添加到購物車”按鈕。 我最初嘗試使用按鈕的點擊事件,但無法從 HTML 產品頁面中提取產品數量和產品名稱。 然后我嘗試在按鈕周圍使用表單標簽,然后使用 post 方法發布產品名稱和產品數量。 當請求到達我的服務器時,我試圖訪問數據(最初只需將其打印出來,以便我可以決定如何將其發布到我的數據庫)但是當我嘗試 request.POST.get('Product Name') 或request.POST.get('Product Quantity') 返回的值為“無”。 當我打印 request.body 時,打印結果是 b'{'Product Name': , 'Product Quantity': 。 我似乎找不到訪問這些數據以供進一步使用的方法。 代碼如下:

{% block scripts %}
<script src="/static/js/addToCart.js" defer></script>
{% endblock %}
{% block content %}
<h1>Get Smart Products</h1>
<div class="container">
    <ul>
    {% for product in product_list %}
        <div class="container">
            <img src="/media/{{product.product_image}}">
            <li>{{ product.name }}</li>
            <li>{{ product.category }}</li>
            <li>{{ product.price }}</li>
            <li>{{ product.description }}</li>
            
            <input type="hidden" value="{{ product.name }}" id="prod_name">
            <label for="Quantity">Quantity</label>
            <div class="input-group text-center mb-3" style="width:130px;">
                <button class="input-group-text decrement-btn">-</button>
                <input type="text" name="quantity" class="form-control qty-input text-center" value="1" id="quantity-btn">
                <button class="input-group-text increment-btn">+</button>
            </div>
            <form action="" method="post">
                {% csrf_token %}<button class="btn btn-danger addToCartBtn" id="addToCartBtn">Add to cart</button>
            </form>
            
        </div>
    {% endfor %}
    </ul>
</div>
{% endblock %}

JS代碼


axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"

document.getElementById("addToCartBtn").addEventListener("click", function(e){
    e.preventDefault();
    const product_input = document.getElementById("prod_name").value
    const product_quantity = Number(document.getElementById("quantity-btn").value)
    console.log(product_input,product_quantity)
    axios.post('/ecomm/addToCart/', {'Product Name': product_input, 'Product Quantity':product_quantity}).then((response)=>{
        console.log(response)
    })
})

django app.views 代碼

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
import requests
from requests_oauthlib import OAuth1
import json
from .models import Product


# Create your views here.
def index(request):
    return render(request, 'home.html', {})

def fin_ed_tech(request):
    product_list = Product.objects.all()
    return render(request, 'get_smart.html', {'product_list': product_list})

def person_pod(request):
    return render(request, 'person_pod_essentials.html', {})

def exoskel_maint(request):
    return render(request, 'exoskeletonal_maintenance.html', {})

def outer_mind_clothing(request):
    return render(request, 'clothing_for_the_outer_mind_wall.html', {})

def about(request):
    return render(request, 'about.html', {})

def search(request):
    return render(request, 'search.html', {})

def search_products(request):

    # print(request.GET.get('query'))
    query = request.GET.get('query')
    
    if Product.objects.filter(name__contains=query):
        db_vars = Product.objects.filter(name__contains=query)
        print(db_vars)
        db_data = list(db_vars.values())
        return JsonResponse({'db_data': db_data})
    else:    
        auth = OAuth1("793746cd4fcf40bda3e1bc6b5b31b277", "e99e19abfa7347cabbf2591bbf8f48e1")
        endpoint = f"http://api.thenounproject.com/icon/{query}"

        API_response = requests.get(endpoint, auth=auth)
        print(API_response.content)
        JSON_API_response = json.loads(API_response.content)
        image_url = JSON_API_response['icon']['preview_url']

        return JsonResponse({'url':image_url})
        # return render(request, 'search_results.html', {})

def addToCart(request):
    if request.method == 'POST':
        prod_name = request.POST.get('Product Name')
        print(prod_name)

    return HttpResponseRedirect('get_smart/')

def Cart(request):
    pass

我得到的錯誤

None
[05/Jul/2022 21:21:09] "POST /ecomm/addToCart/ HTTP/1.1" 302 0
Not Found: /ecomm/addToCart/get_smart/
[05/Jul/2022 21:21:09] "GET /ecomm/addToCart/get_smart/ HTTP/1.1" 404 4124

對於此處使用的所有語言和技術,我是初學者,因此我感謝所有有關操作的建議。 謝謝!

您的字段在您提交的表單之外。 你必須像這樣在里面寫它們:

{% block scripts %}
<script src="/static/js/addToCart.js" defer></script>
{% endblock %}
{% block content %}
<h1>Get Smart Products</h1>
<div class="container">
   <ul>
      {% for product in product_list %}
      <div class="container">
         <img src="/media/{{product.product_image}}">
         <li>{{ product.name }}</li>
         <li>{{ product.category }}</li>
         <li>{{ product.price }}</li>
         <li>{{ product.description }}</li>
         <form action="" method="post">
            <input type="hidden" value="{{ product.name }}" id="prod_name">
            <label for="Quantity">Quantity</label>
            <div class="input-group text-center mb-3" style="width:130px;">
               <button class="input-group-text decrement-btn">-</button>
               <input type="text" name="quantity" class="form-control qty-input text-center" value="1" id="quantity-btn">
               <button class="input-group-text increment-btn">+</button>
            </div>
            {% csrf_token %}<button class="btn btn-danger addToCartBtn" id="addToCartBtn">Add to cart</button>
         </form>
      </div>
      {% endfor %}
   </ul>
</div>
{% endblock %}

另外,我建議發布產品的 id 比它的名稱更好。

暫無
暫無

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

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