[英]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.