简体   繁体   English

从 POST 请求中打印数据时,request.POST.get() 在 Django App 中返回 None

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

I am building an ecommerce web app.我正在构建一个电子商务网络应用程序。 I am trying to build the "add to cart" functionality using some stock html product card code and adding an event listener to the "add to cart" button.我正在尝试使用一些库存 html 产品卡代码构建“添加到购物车”功能,并将事件侦听器添加到“添加到购物车”按钮。 I initially tried to use a click event from the button, but I was unable to pull the product quantity and product name from the HTML product page.我最初尝试使用按钮的点击事件,但无法从 HTML 产品页面中提取产品数量和产品名称。 I then tried to use a form tag around the button, and then post the product name and product quantity using the post method.然后我尝试在按钮周围使用表单标签,然后使用 post 方法发布产品名称和产品数量。 When the request reaches my server, I was trying to access the data (initially by simply printing it out so I can decide how to post it to my database) but when I try the request.POST.get('Product Name') or request.POST.get('Product Quantity') the value returned is "None".当请求到达我的服务器时,我试图访问数据(最初只需将其打印出来,以便我可以决定如何将其发布到我的数据库)但是当我尝试 request.POST.get('Product Name') 或request.POST.get('Product Quantity') 返回的值为“无”。 When I print request.body, the printed result is b'{'Product Name': , 'Product Quantity': .当我打印 request.body 时,打印结果是 b'{'Product Name': , 'Product Quantity': 。 I can't seem to find a way to access this data for further use.我似乎找不到访问这些数据以供进一步使用的方法。 Code Follows:代码如下:

{% 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 code 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 code 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

error I am getting我得到的错误

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

I am a beginner when it comes to all the languages and tech used here so I appreciate all suggestions with what to do.对于此处使用的所有语言和技术,我是初学者,因此我感谢所有有关操作的建议。 Thank you!谢谢!

Your fields are outside the form that you submitted.您的字段在您提交的表单之外。 You have to write them inside like this:你必须像这样在里面写它们:

{% 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 %}

Also, I suggest posting a product's id is better than its name.另外,我建议发布产品的 id 比它的名称更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM