简体   繁体   中英

Django how do we send a model into javascript and render it onto a template

I'm trying to pass a Django model into a template using javascript. I can't seem to filter or do anything with the QuerySet once I get the javascript to read it and pass it on to the template.

My views.py:

def displayDict(request):
    m = ChatStream.objects.filter(name = visitor_ip_address(request))
    last = m.latest('name')
    return render(request, 'chatStream.html',
    {"chat": m, "last": last})

my models.py:

class ChatStream(models.Model):
    bot = models.TextField()
    user = models.TextField()
    name = models.CharField(max_length=100, null=True)
    created_date = models.DateTimeField(auto_now_add=True)

My chatStream.html file:

<p id="demo2">I will display when two seconds have passed.</p>

<script>
    var data = "{{chat}}";
    var lastEntry = "{{last}}"
    } 

setTimeout(myTimeout1, 2000) 


function myTimeout2() {
  document.getElementById("demo2").innerHTML = "2 seconds " + data + "lastEntry" + lastEntry;
}

</script>

The result I get after 2 seconds:

2 seconds <QuerySet [<ChatStream: ChatStream object (31)>, <ChatStream: ChatStream object (32)>]>lastEntryChatStream object (31)

Instead of showing "<QuerySet [<ChatStream: ChatStream object (31)>....] " How do I show the text inside the model named ChatStream?...

I've tried:

<p id="demo2">I will display when two seconds have passed.</p>

<script>
    var data = "{{chat.user}}";
    var lastEntry = "{{last.user}}"
    } 

setTimeout(myTimeout1, 2000) 


function myTimeout2() {
  document.getElementById("demo2").innerHTML = "2 seconds " + data + "lastEntry" + lastEntry;
}

</script>

But the above displays nothing.

I've also tried

<p id="demo2">I will display when two seconds have passed.</p>

<script>
    var data = "{{chat | last }}";
    var lastEntry = "{{last}}"
    } 

setTimeout(myTimeout1, 2000) 


function myTimeout2() {
  document.getElementById("demo2").innerHTML = "2 seconds " + data + "lastEntry" + lastEntry;
}

</script>

but filtering in last throws an error that I can't negative index (and I have the latest version of Django running).

Thanks so much

ChatStream.objects.filter(...) returns a QuerySet which is a list of objects of the ChatStream model, not a single ChatStream model object.

If you want to retrieve a single object of the ChatStream model the use

m = ChatStream.objects.get(name=visitor_ip_address(request))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM