Using javascript to manipulate specific django view variable

Hello guys, im building chat application and i have encountered a problem.

from django.db import models
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User

class Chat(models.Model):
    class chatTypes(models.TextChoices):
        private = 'private', 'private'
        group = 'group', 'group'

    chat_type = models.TextField(choices=chatTypes.choices)
    participants = models.ManyToManyField(User)
    last_message = models.DateTimeField(auto_now=True)
    timestamp = models.DateTimeField(auto_now_add=True)

class Message(models.Model):
    chat_id = models.ForeignKey(Chat, related_name='chat_messages',
    content = models.TextField(max_length=1000)
    sender = models.ForeignKey(User,related_name='user',on_delete=models.CASCADE)
    time_stamp = models.DateTimeField(auto_now_add=True)


def homepage(request):
    chats = Chat.objects.filter(participants=user).prefetch_related('chat_messages').order_by('timestamp')
    var = {
           'chats': chats,
    return render(request, 'homepage.html',var)

now in my template i present the user all his chats in a list

            {% for chat in chats %}
            <div class="chat_item d-flex flex-row">
                <p class="friendly_pic"> pic </p>
                <div class="chat_item_message d-flex flex-column">
                    {% if chat.participants.first == request.user %}
                        <h6> {{ chat.participants.last }} </h6>
                    {% else %}
                        <h6> {{ chat.participants.first }} </h6>
                    {% endif %}
                    <div class="d-flex flex-row justify-content-between  text-muted">
                        <p class="msg"> {{ chat.chat_messages.last.content }} </p>
                        <p class="timer"> {{ chat.chat_messages.last.time_stamp|date:'h:i:A' }} </p>
            <div class="chat_item_separator" style="color:white">
            {% endfor %}

now what i want to do next is to show the chat message next to the chat lists and each time user click on specific chat that website display the chat mark as active but if i want to filter or get the specific chat_messages that related to the active chat i get error
becuase i cant solve it ill give an example:
{% for chat in chats %}
{% if == ${active_chat} %}
print chat content
{% endif %}
{% endfor %}

becuase i know django cant accept ${active_chat} value from javascript i tried to move my if statment into the javascript but i cant seem to make it.
ive tried few solutions came to my mind and all failed please im open to suggestions
thanks for your help :slight_smile:

i have seen someone over the internet who print all chats content in different div cards and each time add .active to the current card but i think over the time (i do it for training but for example if it was aim for production and lets say there is 1000 chats and each chat has 1000 messages it feels like it is idiotic to make the website create all this divs and each time swap between them) but maybe im wrong and it is the correct way

Keep in mind that Django runs in the server. It prepares the page and sends it to the browser. Once the page is sent, the view is done - it’s no longer involved. On the other hand, the JavaScript runs in the browser. It doesn’t even begin to run until after the page has been sent.

If you want the JavaScript to cause something to happen on the server, it does so by making an AJAX-style request to the server, which would cause a view to be executed and return some data. It’s then up to that JavaScript to know what to do with the data being returned.

You need to rethink what you’re trying to do here, and how that’s going to work when coordinating what is supposed to happen in the browser with what happens on the server.

Hey @KenWhitesell first of all thanks for your reply, maybe i didnt presented my thinking in the right way,
what i aim to do is to stay at the same view and not make request to the server but to display different data of the variable i passed in the view (chats) in different situations that depends on what happend inside the browser, maybe an actual working example will be great, if you fimiliar with Whatsapp Web when u click on chat from the chat list it is showing content from that specific chat without making request to the server

That’s where the JavaScript / AJAX comes into play.

Unless you send everything to the browser all-at-once, you’re not going to be able to get away from making subsequent requests to the server.

@KenWhitesell i did send all at once

    chats = Chat.objects.filter(participants=user).prefetch_related('chat_messages').order_by('timestamp')

sends all chats related to the user and each chat with his related messages and my question is how can i switch the display of each chat inside my template
i do know i need to use javascript but all of the javascript solutions i tried have failed so i thought maybe here some django-javascript experts can help me to find the solution i need

Ok, if you’re sending all the data in your initial template being rendered, then this makes it a purely JavaScript issue - Django is not at all involved here.

Your JavaScript needs to show/hide the relevent divs based upon what’s clicked. This has nothing to do with Django - or your template.

The template is rendered once before being sent to the browser. Once the data is sent to the browser, Django doesn’t have any further involvement.

@KenWhitesell Okay I get what you say so I’ll ask this
I want to use the chats I sent through the view
But I want to display specific chat but I can’t do
{{ chats.objects.filter(id=${active_chat}).chat_messages.all }}


You need to define html element references (id or name or even a data field) that your JavaScript can use to identify specific divs. Your JavaScript event handler then needs to use that information supplied in the event to identify which element was clicked, and then toggle the appropriate div to show/hide it.

Correct. This isn’t going to work.

This all needs to be done in JavaScript. It has nothing to do with Django or your template. Stop trying to use Django template-related data here.

Your template will render everything, using some css or attribute to hide the divs. Your JavaScript then un-hides the divs as necessary.

@KenWhitesell In the way you suggest to fix it I do need to loop through all chats with
{{ for chat in chats }}
Then create div for each chat content and stack them in a pile and each time show one
But my question here isn’t a waste of memory to create a lot of divs for the purpose of showing only one each time?

Yes it is.

That’s why the general recommendation is that you render and send only what you need, then make an AJAX call to retrieve details as necessary.