3

I have desktop application which creates SqLite DB.

I would like to use that data to make reports on a local static web page. However I'm not sure how to go about connecting to an existing DB - I understand there are security issues with this.

is this possible with JavaScript ? and how would i go about this ?

Mrparkin
  • 65
  • 10

2 Answers2

2

One option is to pass the data from the templates like so:

def index(request):
    # Calculate your precious data here, for example using the django.core.serializers class:
    data = serializers.serialize('json', FooModel.objects.all())
    return render(request, 'templates/index.html', {'data': data})

Then in your templates/index.html you could do something like this:

<script>
    window.data = {{data|default:"{}"|safe}};
</script>

Check out the safe filter.

This way, you get all your data from backend to frontend with your initial request without creating any additional requests, or communicating with your DB directly with JS.


Another option is using fetch:

You could create a view (you could use Django REST framework but that's up to what you're trying to use it for, the main idea remains the same anyway):

from django.http import HttpResponseNotAllowed, JsonResponse
from django.core import serializers
from .models import FooModel # for example

def myview(request):
    if request.method != "POST":
        return HttpResponseNotAllowed(['POST'], "Only POST is allowed to this URL.")
    # Get your precious data, let's use the same example as before:
    data = serializers.serialize('json', FooModel.objects.all())
    return JsonResponse(data)

Register it in your urls.py:

urlpatterns = [
    ...
    path('api/retrievepreciousdata', views.myview),
    ...
]

And then we can use fetch to retrieve it:

fetch("/api/retrievepreciousdata", {
    method: "POST",
    headers: {
        //For CSRF protection:
        //I use `js-cookie` to get the cookies, it's up to you really
        "X-CSRFToken": Cookies.get("csrftoken"),
        "X-Requested-With": "XMLHttpRequest",
    },
}).then(response => {
    if(!response.ok) {
        console.log("Dang it, the response isn't OK... Response code is", response.status);
    }
    return response.json()
}).then(json => {
    console.log("I did it! My precious data is:", json);
}).catch(e => {
    console.log("Dang it, something went wrong while retrieving my precious data:", e);
});
NonameSL
  • 1,405
  • 14
  • 27
0

If you are looking for a way to read data from SQLlite Db from a static webpage I suggest you read the following thread Is it possible to access an SQLite database from JavaScript?

Try this also SQL.js (its mention in the above thread)

Tiisetso Tjabane
  • 2,088
  • 2
  • 19
  • 24