What is the best way to implement two for loops in a Django template to handle sending and receiving chat messages efficiently?

I am attempting to implement sending and receiving messages in a Django template using a for loop. Here is my views function:

@login_required
def message_form(request, id, slug, user_id):

    user2 = request.user
    user_id = user_id
    user = get_object_or_404(User, id=user_id)
    msg = Message.objects.filter(sender=user)
    post = get_object_or_404(Post, id=id, slug=slug)
    post2 = Post.objects.filter(user=post.user)
    inbox = Message.objects.filter(reciever=request.user)
    sentbox = Message.objects.filter(sender=request.user)
    message1 = Message.objects.filter(post=post, sender=user, reciever=post.user).order_by('date')

    message2 = Message.objects.filter(post=post, sender=post.user, reciever=user).order_by('date')

reverse=True))

    form = MessageForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            message = form.save(commit=False)
            if post.user == request.user:
                message.sender = post.user
                message.reciever = user
            else:
                message.sender = request.user
                message.reciever = post.user

            message.post = post
            message.post_user = post.user
            message.post_image = post.image1
            message.save()
           
            form = MessageForm()
            return HttpResponseRedirect('')

    context = {
        'post': post,
        'post2': post2,
        'inbox': inbox,
        'sentbox': sentbox,
        'form': form,
        'message1': message1,
        'user_id': user_id,
        'msg': msg,
        'message2': message2,
    }

    return render(request,'chat.html',context)

And this is the relevant part of the chat.html template:

<div class="border px-2 chat-box">
    {% for box in message1 %}
        <div class="my-4 border bg-light">
          <span class="p-2 my-5">{{ box.msg_content }}</span><br>
          <span class="date text-muted">{{ box.whenpublished }}</span>
        </div>
    {% endfor %} 

    {% for box2 in message2 %}
        <div class="border bg-danger" style="">
            <span class="p-2 my-5">{{ box2.msg_content }}</span><br>
            <span class="date text-muted">{{ box2.whenpublished }}</span>
        </div>
    {% endfor %}
</div>

Currently, each sent and received message displays separately. However, I would like the sent message to appear after the received message like this:

hello(user1)

hello(user2)

how are you(user1)

im fine thanks(user2)

Answer №1

It appears that the question may not be fully comprehended, however, it seems like resolving this issue should be done in the views.py file.

views.py

import operator
from itertools import chain

def solve_problem(request):
    '''
    message1 = "call user1's message"
    message2 = "call user2's message"
    message = list(chain(message1, message2))
    message = sorted(message, key=operator.attrgetter('whenpublished', reverse=True)
    '''

    return render(requeset, "YOUR HTML FILE", {
      'message': message,
    }

html

<div class="border px-2 chat-box ">
    {% for box in message %}
    <div class=" my-4 border bg-light ">
        <span class=" p-2 my-5">{{ box.msg_content }}</span><br>
        <span class="date text-muted ">{{ box.whenpublished }}</span>
    </div>
    {% endfor %} 
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I encountered an issue while making customizations to my default next.config.js file. Despite attempting various solutions, I consistently encountered an error regarding the invalid src property

I'm currently trying to introduce some custom configurations into the next.config.js file. However, I keep encountering an error regarding an invalid src prop. Despite my attempts to troubleshoot in various ways, the error persists. // ...

What is the process for obtaining a JSON file in AngularJS upon clicking a button?

Starting off with AngularJS and feeling excited. I have successfully created a form with two input boxes. Just below the input boxes, I have added: <input ng-model="id.todoList" type="text" name="input" placeholder="Enter tasks here"> <input ng ...

In Vue, emitting does not trigger the parent component to update its properties

The emit is functioning properly, as I can observe in the vue developer tool. However, the property in the parent element is not updating. Child Component: <template> <div> <ul> <li v-for="(option, index) in opt ...

What causes the function to return null when using router.get('/:x',..), whereas router.get('/foo/:x',...) works perfectly fine?

After weeks of struggling to identify the root cause of my issue, I finally pinpointed it. Now, I'm curious to understand the reason behind this behavior. I constructed an api for my mongodb server following the techniques I learned in school, utiliz ...

Personalizing the service endpoint in Feathers.js: A guide

Is there a way to attach a URL to my user requests that reside in a different service? How can I customize a GET request? const { Service } = require('feathers-sequelize') exports.Users = class Users extends Service { get(id, params) { // ...

Achieving stylish CSS effects on dynamically loaded content post AJAX request

I am currently developing an application that utilizes AJAX to fetch JSON data and then uses an ES6 template literal to construct the view. It's a simple demonstration: let mountPoint = document.getElementById("mountPoint"); let view = document.cre ...

Using Vaadin: update Label text with TextField input after Button is clicked

I'm working on a simple Vaadin form where I want the text entered in a TextField to appear in a Label after the user clicks on a Button. Here's the code snippet: package com.example; import javax.servlet.annotation.WebServlet; import com.vaad ...

Steps for incorporating the count() value in Django for web developmentTo embed the count() value while creating

I'm currently working on a web visual board project using Django. Here is the specific HTML section where I need to populate values from the database: <tbody> {% for obj in data_list %} <tr> <th>{{ ob ...

Issue with Backbone.Marionette: jQuery document.ready not executing when on a specific route

I am dealing with a situation in my web application where the document.ready() block is not being executed when the page routes from the login button to the dashboard. I have an initialize() function that contains this block, but it seems like there is an ...

ReactJS encountering an invalid dropzone element

Encountering the error "invalid dropzone element". I added var Dropzone = require('react-dropzone'); to my webpack.config.js file in hopes of activating the Dropzone element. This is what is included in my JavaScript file, copied from a Gith ...

Having trouble getting Selenium to function properly for testing my Django Channels application

I am having trouble testing my app with Selenium. Even the most basic actions result in a long error message that I can't seem to understand. I am new to using Selenium and these errors are confusing me. I would greatly appreciate any help. My app is ...

Tips for implementing an onClick event within a NavBar component in a React application

Embarking on my first React project has been an exciting journey for me. I am relatively new to JavaScript, HTML, CSS, and the world of web app programming. My goal is to showcase some information upon clicking a button. In my main default component, App ...

Encountering a 404 error while attempting to retrieve data from Node.js within a React.js application despite the server being operational

This is my first time delving into the world of back-end development, and it's quite challenging for me. The tech stack I'm using includes React.js, Node.js, express.js, and mysql. However, when I try to fetch the result of a query, I keep runnin ...

Next.js has a problem where it displays incorrect data when users navigate rapidly between pages

An unusual challenge has emerged while rendering data on a Next.js page in my application. Here's the scenario: I've created a Next.js page that showcases customer details based on a query parameter called cid. The page retrieves customer data an ...

Lack of y data in the Highcharts

I am facing an issue with retrieving yAxis data in Highcharts. You can view the fiddle at https://jsfiddle.net/LLExL/6496/. I have loaded Highcharts using the code below. $(function () { $('#RankingReportsHistory').highcharts( ...

How does the interaction between Express and Angular for routing in the MEAN Stack function?

Currently, I am utilizing Express static to direct to the public directory. //app.js app.use(express.static( __dirname + '/public')); I am looking for a way to have most of the UI routing done by AngularJS. However, it seems that it only works ...

Apply a chosen style to the element that was clicked on, while removing the style from the rest

Here is an example of my ul li structure: <div id="categoryTree"> <ul> <li id="cat_15"> <a class="hasSubCat" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">N ...

What is the appropriate HTTP status code for "item not found" when using RESTful ajax?

Imagine having a single-page web application featuring a list of items. Users can click on an item to view more information about it. The details of each item are loaded asynchronously via an AJAX GET request to the URL http://www.example.com/item/[id], an ...

Calculate the difference in days between two selected dates from an Ajax Datetime Picker using JavaScript

How can I use JavaScript to count the number of days between two selected dates from Ajax date time pickers in my aspx page? The script should automatically input this calculated value into a designated "Number_Of_Days" text box without requiring a page ...

Rapid processing of JavaScript upon page load

I recently implemented a dark mode feature on my WordPress site. Here are the four modes I included: 1- Automatically based on user's system settings 2- Light mode 3- Semi-lit mode 4- Dark mode The implementation is in place and functioning perf ...