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);
});