从POST请求打印数据时,请request.post.get()在Django应用中返回无返回
我正在构建一个电子商务网络应用程序。我正在尝试使用一些库存HTML产品卡代码构建“添加到购物车”功能,并将事件侦听器添加到“添加到购物车”按钮中。我最初尝试使用按钮中的点击事件,但是我无法从HTML产品页面中提取产品数量和产品名称。然后,我尝试在按钮周围使用表单标签,然后使用Post方法发布产品名称和产品数量。当请求到达我的服务器时,我正在尝试访问数据(最初仅将其打印出来,以便我可以决定如何将其发布到我的数据库中) request.post.get('产品数量')返回的值是“无”。当我打印请求时,印刷结果为b'{'product name':,'产品数量':。我似乎找不到访问此数据以供进一步使用的方法。代码如下:
{% 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。查看代码
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
我是初学者,因此我感谢所有建议的建议。谢谢你!
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. 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. I then tried to use a form tag around the button, and then post the product name and product quantity using the post method. 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". When I print request.body, the printed result is 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
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
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的字段不在您提交的表格之外。您必须这样的内部写入它们:
另外,我建议发布产品ID胜于其名称。
Your fields are outside the form that you submitted. You have to write them inside like this:
Also, I suggest posting a product's id is better than its name.