I'm writing a simple Django + React Application in which I want to pass some JSON from Django render() to React.js. I first render an HTML page with Django, providing the JSON. Although I'm unaware of the format, the data is coming through, as I can show it using Django's template language. However, in the React code, which is called by the HTML page, I get the JSON as a string, and only the first 10 chars. I'm wondering whether there is a way to get this through properly, instead of having to write an http post every time.
My Django views script, which renders the html:
@login_required(login_url="/login/")
def index(request):
data = {
'key': [0, 1, 2, 3],
'key2': 'abcd',
}
context = {
'data': json.dumps(data),
'navItem': 0,
}
return render(request, "index.html", context)
My index.html:
<!DOCTYPE html>
<html lang="en">
<body>
{{data}}
<div class="reactitem" data-json={{data}}></div>
<script src="http://127.0.0.1:8080/index.js" charset="utf-8"></script>
</body>
</html>
And lastly my index.js (locally hosted):
document.querySelectorAll('#reactitem').forEach((domContainer) => {
console.log(domContainer.dataset.json);
console.log(typeof(domContainer.dataset.json));
console.log(domContainer.dataset.json.length);
})
When I load the page, I see the full data json on screen while getting the following output in the console:
{"key":
string
7