1

I'm having hard times to find a way to use my Django returned data on the clientside. I think I mix up several concepts here.

This is my view that calls the model StocksPrice and returns all data in the table column stockName:

def getStocksAvailable(request, *args, **kwargs):
    StocksAvailable = serializers.serialize('json', StocksPrice.objects.values(stockName))
    return HttpResponse({"data": StocksAvailable})

and according Javascript part for testing purposes:

var received_data = "{{ StocksAvailable }}"
    console.log(received_data);

# Outputs: {{ StocksAvailable }}

I also tried it using render in the view:

def getStocksAvailable(request, *args, **kwargs):
    StocksAvailable = serializers.serialize('json', StocksPrice.objects.values(stockName))
    return render({"data": StocksAvailable})

Why does JS logs it as a string whereas it is supposed to be a variable containing the returned json object? And how could I basically print the returned data from the view for debugging (maybe s.th. is wrong with the json itself)?

Updated Version @Willems response

Url mapping:

urlpatterns = [

    path('terminal/getStocksAvailable/', get_stocks_available),
]

View

def get_stocks_available(request, *args, **kwargs):
    stocks_available = serializers.serialize('json', StocksPrice.objects.values(stockName))
    return JsonResponse({'data': json.loads(stocks_available)})

Model

class StocksPrice(models.Model):
    stockName = models.CharField(max_length=100, blank=False)
     [...]

    class Meta:
        db_table = 'StocksPrice'

JS

$( document ).ready(function() {
    $.ajax('getStocksAvailable/', {
        method: 'GET',
        async: "True",
        dataType: "json",
        success: function () {
            var received_data = "{{stocks_available}}"
            console.log(received_data);
        }
    })
});

which now throws:

Traceback (most recent call last):
  File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Jonas\Desktop\CFD\CFD\terminal\views.py", line 10, in get_stocks_available
    stocks_available = serializers.serialize('json', StocksPrice.objects.values(stockName))
NameError: name 'stockName' is not defined
[17/May/2020 14:36:56] "GET /terminal/getStocksAvailable/ HTTP/1.1" 500 16181
[17/May/2020 14:36:56] "GET /terminal/getStocksAvailable/ HTTP/1.1" 500 16181

1 Answer 1

1

Why does JS logs it as a string whereas it is supposed to be a variable containing the returned json object?

Because serializers.serialize(..) returns a string. If you want to wrap it in an object, you can for example decode it:

import json
from django.http import JsonResponse

def get_stocks_available(request, *args, **kwargs):
    stocks_available = serializers.serialize('json', StocksPrice.objects.values(stockName))
    return JsonResponse({'data': json.loads(stocks_available)})

EDIT1:

You furthermore need to pass a value for stockName, and process the result.view_data (this is a parameter in the data):

$( document ).ready(function() {
    $.ajax('getStocksAvailable/?stockName=???', {
        method: 'GET',
        async: "True",
        dataType: "json",
        success: function (result) {
            var received_data = result.view_data;
            console.log(received_data);
        }
    })
});

with ??? to fill in.

in the view, you can then access request.GET to obtain the value for stockName:

import json
from django.http import JsonResponse

def get_stocks_available(request, *args, **kwargs):
    stockName = request.GET['stockName']
    stocks_available = serializers.serialize('json', StocksPrice.objects.values(stockName))
    return JsonResponse({'data': json.loads(stocks_available)})

EDIT2:

If you want to use values from a column named stockName, then you should use:

import json
from django.http import JsonResponse

def get_stocks_available(request, *args, **kwars):
    stocks_available = serializers.serialize('json', StocksPrice.objects.values('stockName'))
    return JsonResponse({'data': json.loads(stocks_available)})

and at the JavaScript side:

$( document ).ready(function() {
    $.ajax('getStocksAvailable/', {
        method: 'GET',
        async: "True",
        dataType: "json",
        success: function (result) {
            var received_data = result.view_data;
            console.log(received_data);
        }
    })
});
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for the prompt support. I replaced it with your view, but the clientside still does not log the data. I guess I am still missing s.th. here :/
@Phanti: how exactly do you fetch the data? With an AJAX request?
What I mean is: getStocksAvailable returns a Json blob, you have some JavaScript I assume that triggers this view, and process the data?
sorry for the missing input. I have an AJAX call upon document.ready
Ah, but you did not define a value for stockName., see edit.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.