Pachvarsh Pachvarsh - 2 months ago 12
Python Question

How to get information from SQLite using JQuery with Django?

I have a project in Django. In a Python view script i made an array and add this value to my SQLite database "db.sqlite3" by

request.user.profile.some_array = some_array


Next i sent this array to HTML file this way:

return render(request,'field.html',{'some_array': some_array})


The "field.html" is connected with the "app.js" with:

script src="{% static 'app.js' %}


I need to get the access from 'app.js' to "some_array" that is stored in database "db.sqlite3" (at the position "user.profile.some_array" if using Python), make several changes with JavaScript and save it.

The Internet community advices to use AJAX, but i can't find example i need. Could you help me?

P.S. I use the Pycharm

Answer

Community advices AJAX, because it's the way that your script in client's browser communicate with you server "in background". But to use it, you will still need API, or some Django Views that will get your AJAX's requests, make some operations, and send response. Learn more about AJAX on w3schools and from jQuery docs.

But for basic solution you need two things - proper AJAX requests and some Django's API with Views to handle them.

Let's start with API, create two urls for our script:

url(r'^api/get_array/(?P<uid>\d+)$', views.GetArrayView.as_view(), name='get_array'),
url(r'^api/save_array$', views.SaveArrayView.as_view(), name='save_array'),

First View will get user by given id, then send back it's array (as JSON).

Second View will get POST data and save it into database.

from django.http import JsonResponse 

class GetArrayView(View):

    def get(self, request, uid):
        # some operations to get array from database using user ID given in uid parameter
        # array is a list, just like one in your question
        return JsonResponse({'array': array})

class SaveArrayView(View):

    def post(self, request):
        post = request.POST
        changed_array = post.get('array')
        user_id = post.get('uid')
        # some operations to save your array into database
        return JsonResponse({'status': OK})

About JSON responses, read this. And now, AJAX. To get array, in your script use:

$.ajax({
    type: "GET",
    url: '/api/get_array/'+user_id,
    success: function(response){
        // your array is in the response.array
    },
    error: function(jqXHR, textStatus, errorThrown){
        // handle any errors here
    }
});

$.ajax({
    type: "POST",
    url: '/api/save_array/',
    data:{
        array: your_changed_array,
        uid: user_id,
        some_other_data: other_data,
    },
    success: function(response){
        if(response.status == "OK"){
            // everything went fine
        }
        else{
            // you can send other responses and handle them here
        }
    },
    error: function(jqXHR, textStatus, errorThrown){
        // handle any errors here
    }
});

This is the very basic setup, I encourage you to read more about AJAX requests and Django REST Framework API (great framework for JSON GET/POST/UPDATE/DELETE api).

One last thing - every POST request in Django need CSRF token. Using them in JavaScript is complicated, here's docs for that. If you want shortcut, you can turn it off for chosen View, but I do not recommend it. More info here.