Error in Django Get request that dosen't make sense












0















I have a basic Django app right now which allows users to add items to a database. When the product is added, the list of items should update when a new item is added via the form, and display that Product and all the other Products already in the database. Here is the code I have so far:



This is the views.py file with my current implementation of the method that should get the products at the bottom:



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)


The index.html page:



<!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>


And the urls.py file:



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)
]


So far, adding a product in is fine and causes no issues. However, after writing the getData() method and including it, this part dosen't work and returns the following error:



File "C:UsersinstallDocumentstutorialproductsviews.py", line 29, in viewProduct 
ProductList = Product.objects.all()
UnboundLocalError: local variable 'Product' referenced before assignment


I'm confused by this error as I'm not assigning Product anywhere else in this file so not sure why it's returning this error. When I do this same assignment in the Shell, it doesn't have a problem with it and returns all the objects. Can someone help me resolve this? Thanks.










share|improve this question




















  • 1





    Here: for Product in ProductList: Don't use the variable names that clash with class/method names. That's why you should follow PEP8 and name your variables in lowercase (i.e. for product in product_list).

    – Selcuk
    Nov 13 '18 at 23:38











  • @Selcuk changed it to your advice, still returns the same 'local variable referenced before assignment error'

    – Arsenalfan
    Nov 13 '18 at 23:41











  • Did you restart your server?

    – Selcuk
    Nov 13 '18 at 23:51











  • Yes, restarted a few times

    – Arsenalfan
    Nov 14 '18 at 2:39











  • Not sure what went wrong as the answer you've accepted is exactly the same as my comment. Glad that you resolved it though :)

    – Selcuk
    Nov 14 '18 at 2:53


















0















I have a basic Django app right now which allows users to add items to a database. When the product is added, the list of items should update when a new item is added via the form, and display that Product and all the other Products already in the database. Here is the code I have so far:



This is the views.py file with my current implementation of the method that should get the products at the bottom:



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)


The index.html page:



<!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>


And the urls.py file:



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)
]


So far, adding a product in is fine and causes no issues. However, after writing the getData() method and including it, this part dosen't work and returns the following error:



File "C:UsersinstallDocumentstutorialproductsviews.py", line 29, in viewProduct 
ProductList = Product.objects.all()
UnboundLocalError: local variable 'Product' referenced before assignment


I'm confused by this error as I'm not assigning Product anywhere else in this file so not sure why it's returning this error. When I do this same assignment in the Shell, it doesn't have a problem with it and returns all the objects. Can someone help me resolve this? Thanks.










share|improve this question




















  • 1





    Here: for Product in ProductList: Don't use the variable names that clash with class/method names. That's why you should follow PEP8 and name your variables in lowercase (i.e. for product in product_list).

    – Selcuk
    Nov 13 '18 at 23:38











  • @Selcuk changed it to your advice, still returns the same 'local variable referenced before assignment error'

    – Arsenalfan
    Nov 13 '18 at 23:41











  • Did you restart your server?

    – Selcuk
    Nov 13 '18 at 23:51











  • Yes, restarted a few times

    – Arsenalfan
    Nov 14 '18 at 2:39











  • Not sure what went wrong as the answer you've accepted is exactly the same as my comment. Glad that you resolved it though :)

    – Selcuk
    Nov 14 '18 at 2:53
















0












0








0








I have a basic Django app right now which allows users to add items to a database. When the product is added, the list of items should update when a new item is added via the form, and display that Product and all the other Products already in the database. Here is the code I have so far:



This is the views.py file with my current implementation of the method that should get the products at the bottom:



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)


The index.html page:



<!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>


And the urls.py file:



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)
]


So far, adding a product in is fine and causes no issues. However, after writing the getData() method and including it, this part dosen't work and returns the following error:



File "C:UsersinstallDocumentstutorialproductsviews.py", line 29, in viewProduct 
ProductList = Product.objects.all()
UnboundLocalError: local variable 'Product' referenced before assignment


I'm confused by this error as I'm not assigning Product anywhere else in this file so not sure why it's returning this error. When I do this same assignment in the Shell, it doesn't have a problem with it and returns all the objects. Can someone help me resolve this? Thanks.










share|improve this question
















I have a basic Django app right now which allows users to add items to a database. When the product is added, the list of items should update when a new item is added via the form, and display that Product and all the other Products already in the database. Here is the code I have so far:



This is the views.py file with my current implementation of the method that should get the products at the bottom:



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)


The index.html page:



<!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>


And the urls.py file:



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)
]


So far, adding a product in is fine and causes no issues. However, after writing the getData() method and including it, this part dosen't work and returns the following error:



File "C:UsersinstallDocumentstutorialproductsviews.py", line 29, in viewProduct 
ProductList = Product.objects.all()
UnboundLocalError: local variable 'Product' referenced before assignment


I'm confused by this error as I'm not assigning Product anywhere else in this file so not sure why it's returning this error. When I do this same assignment in the Shell, it doesn't have a problem with it and returns all the objects. Can someone help me resolve this? Thanks.







python jquery django get request






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 23:39









Joel

1,5706719




1,5706719










asked Nov 13 '18 at 23:30









ArsenalfanArsenalfan

135




135








  • 1





    Here: for Product in ProductList: Don't use the variable names that clash with class/method names. That's why you should follow PEP8 and name your variables in lowercase (i.e. for product in product_list).

    – Selcuk
    Nov 13 '18 at 23:38











  • @Selcuk changed it to your advice, still returns the same 'local variable referenced before assignment error'

    – Arsenalfan
    Nov 13 '18 at 23:41











  • Did you restart your server?

    – Selcuk
    Nov 13 '18 at 23:51











  • Yes, restarted a few times

    – Arsenalfan
    Nov 14 '18 at 2:39











  • Not sure what went wrong as the answer you've accepted is exactly the same as my comment. Glad that you resolved it though :)

    – Selcuk
    Nov 14 '18 at 2:53
















  • 1





    Here: for Product in ProductList: Don't use the variable names that clash with class/method names. That's why you should follow PEP8 and name your variables in lowercase (i.e. for product in product_list).

    – Selcuk
    Nov 13 '18 at 23:38











  • @Selcuk changed it to your advice, still returns the same 'local variable referenced before assignment error'

    – Arsenalfan
    Nov 13 '18 at 23:41











  • Did you restart your server?

    – Selcuk
    Nov 13 '18 at 23:51











  • Yes, restarted a few times

    – Arsenalfan
    Nov 14 '18 at 2:39











  • Not sure what went wrong as the answer you've accepted is exactly the same as my comment. Glad that you resolved it though :)

    – Selcuk
    Nov 14 '18 at 2:53










1




1





Here: for Product in ProductList: Don't use the variable names that clash with class/method names. That's why you should follow PEP8 and name your variables in lowercase (i.e. for product in product_list).

– Selcuk
Nov 13 '18 at 23:38





Here: for Product in ProductList: Don't use the variable names that clash with class/method names. That's why you should follow PEP8 and name your variables in lowercase (i.e. for product in product_list).

– Selcuk
Nov 13 '18 at 23:38













@Selcuk changed it to your advice, still returns the same 'local variable referenced before assignment error'

– Arsenalfan
Nov 13 '18 at 23:41





@Selcuk changed it to your advice, still returns the same 'local variable referenced before assignment error'

– Arsenalfan
Nov 13 '18 at 23:41













Did you restart your server?

– Selcuk
Nov 13 '18 at 23:51





Did you restart your server?

– Selcuk
Nov 13 '18 at 23:51













Yes, restarted a few times

– Arsenalfan
Nov 14 '18 at 2:39





Yes, restarted a few times

– Arsenalfan
Nov 14 '18 at 2:39













Not sure what went wrong as the answer you've accepted is exactly the same as my comment. Glad that you resolved it though :)

– Selcuk
Nov 14 '18 at 2:53







Not sure what went wrong as the answer you've accepted is exactly the same as my comment. Glad that you resolved it though :)

– Selcuk
Nov 14 '18 at 2:53














1 Answer
1






active

oldest

votes


















3














The problem is here:



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)


You have to change for Product in ProductList to Something else like for _Product in ProductList



Try this one:



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)





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53291021%2ferror-in-django-get-request-that-dosent-make-sense%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    The problem is here:



    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)


    You have to change for Product in ProductList to Something else like for _Product in ProductList



    Try this one:



    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)





    share|improve this answer






























      3














      The problem is here:



      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)


      You have to change for Product in ProductList to Something else like for _Product in ProductList



      Try this one:



      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)





      share|improve this answer




























        3












        3








        3







        The problem is here:



        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)


        You have to change for Product in ProductList to Something else like for _Product in ProductList



        Try this one:



        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)





        share|improve this answer















        The problem is here:



        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)


        You have to change for Product in ProductList to Something else like for _Product in ProductList



        Try this one:



        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)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 13 '18 at 23:45

























        answered Nov 13 '18 at 23:40









        DarkSuniuMDarkSuniuM

        7861019




        7861019






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53291021%2ferror-in-django-get-request-that-dosent-make-sense%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Florida Star v. B. J. F.

            Error while running script in elastic search , gateway timeout

            Adding quotations to stringified JSON object values