Django Get请求中的错误,没有意义

时间:2018-11-13 23:30:30

标签: python jquery django get request

我现在有一个基本的Django应用,允许用户向数据库添加项目。添加产品时,通过表单添加新项目时,项目列表应更新,并显示该产品和数据库中已有的所有其他产品。这是我到目前为止的代码:

这是views.py文件,其中包含该方法的当前实现,应该将产品放在底部:

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from products.models import Product
from django.http import HttpResponse, JsonResponse

def index(request):
    return render(request, 'index.html')

@csrf_exempt
def createProduct(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        description = request.POST.get('description')
        price = request.POST.get('price')

        newProduct = Product(
            name = name,
            description = description,
            price = price
        )

        newProduct.save()

        return HttpResponse('')


def viewProduct(request):
    if request.method == 'GET':
        ProductList = Product.objects.all()
        products=[]
        for Product in ProductList:
            products.append({"name": Product.name, "description": Product.description, "price": Product.price})
    return JsonResponse(products)

index.html页面:

<!DOCTYPE html>
<html>
<body>
  <div>
  <h2 id="title">Create product</h2>
  <input id="name">Name</input>
  <br>
  <input id="description">Description</input>
  <br>
  <input id="price">Price</input>
  <br>
  <button id="add-product">ADD PRODUCT</button>
  </div>

  <div id="productList">
  </div>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script type="text/javascript">

  document.getElementById('add-product').onclick =  function(){
    sendData();
    getData();
  }
function sendData(){
  var order = {
  name: document.getElementById('name').value,
  description: document.getElementById('description').value,
  price: document.getElementById('price').value
 };

 $.ajax({
  type: "POST",
  url: 'create/product',
  data: order,
  success: function(newProduct){
    console.log("success"),
    $('#name').val(""),
    $('#description').val(""),
    $('#price').val("")
  }
 });
};

function getData(){
  $.ajax({
    url: 'view/product',
    dataType: 'json',
    type: 'GET',
    success: function(data){
      $.each(data.Product, function(index, element){
        $('body').append($('productList', {
          text: element.name
        }));
      });
    }
  });


}

</script>

</html>

还有urls.py文件:

from django.contrib import admin
from django.urls import path
from products import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
    path('create/product', views.createProduct),
    path('view/product', views.viewProduct)
]

到目前为止,添加产品还可以,没有任何问题。但是,在编写getData()方法并将其包括在内之后,该部分将无法工作并返回以下错误:

File "C:\Users\install\Documents\tutorial\products\views.py", line 29, in viewProduct 
ProductList = Product.objects.all() 
UnboundLocalError: local variable 'Product' referenced before assignment

这个错误让我感到困惑,因为我没有在该文件的其他任何地方分配产品,所以不确定为什么会返回此错误。当我在Shell中进行相同的分配时,它没有任何问题,并返回了所有对象。有人可以帮我解决这个问题吗?谢谢。

1 个答案:

答案 0 :(得分:4)

问题在这里:

def viewProduct(request):
    if request.method == 'GET':
        ProductList = Product.objects.all()
        products=[]
        for Product in ProductList: # <= This is where cause the problem
            products.append({"name": Product.name, "description": Product.description, "price": Product.price})
    return JsonResponse(products)

您必须将for Product in ProductList更改为for _Product in ProductList

尝试这个:

def viewProduct(request):
        if request.method == 'GET':
            ProductList = Product.objects.all()
            products=[]
            for prod in ProductList:
                products.append({"name": prod.name, "description": prod.description, "price": prod.price})
        return JsonResponse(products)