I've checked this stackoverflow topic , but this snippet doesn't work for me. I've got an error: 'Template' object has no attribute 'nodelist'. My data is not displayed in template. My goal is to refresh the data of an already rendered page, so updating a single block from a template. My code is as follow:
views.py:
def my_view(request):
if request.is_ajax():
my_data = MyObject.objects.all()
ctx = { 'test': my_data.values()}
return render(request, "temp.html", context=ctx)
I can see my JSON data in Chrome console after submitting AJAX request , but this data is not displayed in the template.
my template:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
{% for v in test %}
{{ v.path }}
{% endfor %}
<script>
window.setInterval(function(){
$(document).ready(function() {
$.ajax({
async: true,
type: "GET",
url: "/requests/",
});
});
}, 2000);
</script>
I see v.path data in Chrome console.
my json data has the following structure:
[
{
"pk":4233,
"model":"hello.webrequest",
"fields":{
"method":"GET",
"meta":"",
"user":null,
"is_secure":false,
"raw_post":"",
"user_agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36",
"host":"127.0.0.1:8765",
"path":"/requests/",
"cookies":"{\"sessionid\": \"1t0ect4zsnfdh5ght7kqhmf3soezueg1\", \"csrftoken\": \"yLImX79fUFJD7kpGQCcfBZawwFtOUcFR\"}",
"remote_addr_fwd":null,
"status_code":200,
"time":"2015-12-17T15:38:04.242Z",
"post":null,
"remote_addr":"127.0.0.1",
"get":null,
"uri":"http://127.0.0.1:8765/requests/",
"is_ajax":false
}
}
]
Also, I've tried HttpResponse, but It doesn't work for me too
Could you please provide some 100% working example?
In this topic Render JSON objects through Django template-tag i've found such advice:
if the json comes from your own application, you could return an html fragment instead of json.
But I don't quite understand how can I do this.
UPDATE: i've solved my problem. I refused to use django template tag. Instead of this, I just pass JSON into jQuery script and generate required html.