Show elements in reverse order, mimicking the layout of Facebook messages

Is there a way to organize elements from bottom to top, similar to how Facebook messages are displayed? Any suggestions on achieving this?

html:

<div id="message_wrapper">
    <div class="message">
        <p>1 Message message message....</p>
    </div>
    <div class="message">
        <p>2 Message message message....</p>
    </div>
    <div class="message">
        <p>3 Message message message....</p>
    </div>
    <div class="message">
        <p>4 Message message message....</p>
    </div>
</div>

This arrangement would display as follows:

4 Message message message....
3 Message message message....
2 Message message message....
1 Message message message....

Update: Added django tempate

The template for conversation.html looks like this:

<div id="messages_wrapper">

<!-- Displaying recent conversations in the thread -->
{% if conversations != 0 %}
<p><b>You have conversations:</b></p>

    <!-- Checking messagestate of each message in the recent_thread -->
    {% if recent_thread|all_message_hidden:user %}
        <p>All messages are hidden</p>

    {% else %}


        {% for conversation in conversations %}

            {% if conversation|conversation_hidden:user %}

                {% if conversation.sender == user %}
                    <div id="conversation" class="user_sent_conversation">
                        <p>{{conversation.id}}-{{conversation.body}} : Sender- {{conversation.sender}}, ID {{conversation.sender.id}}</p>
                        <p>Already hidden</p>
                    </div>
                    <hr/>
                {% else %}
                    <div id="conversation" class="others_sent_conversation">
                        <p>{{conversation.id}}-{{conversation.body}} : Sender- {{conversation.sender}}, ID {{conversation.sender.id}}</p>
                        <p>Already hidden</p>
                    </div>
                    <hr/>
                {% endif %}

            {% else %}
                {% if conversation.sender == user %}
                    <div id="conversation" class="user_sent_conversation">
                        <p>{{conversation.id}}-{{conversation.body}} : Sender- {{conversation.sender}}, ID {{conversation.sender.id}}</p>
                        <a href="/inbox/delete_conversation/{{conversation.id}}/">[X]</a>
                    </div>
                    <hr/>
                {% else %}
                    <div id="conversation" class="others_sent_conversation">
                        <p>{{conversation.id}}-{{conversation.body}} : Sender- {{conversation.sender}}, ID {{conversation.sender.id}}</p>
                        <a href="/inbox/delete_conversation/{{conversation.id}}/">[X]</a>
                    </div>
                    <hr/>
                {% endif %}

            {% endif %}

        {% endfor %}


        <div id="message_form_wrapper_inside">
            {% if messages %}
            <ul class="messages">
                {% for message in messages %}
                <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
                {% endfor %}
            </ul>
            {% endif %}

            <form action="/inbox/send_messages/{{recent_thread|get_user_id:user}}/" method="post">
                {% csrf_token %}
                <label for="recipient">To - {{recent_thread|get_user_id:user}}</label>

                <label for="subject">
                    Subject - 
                    {% if recent_thread.subject != '' %}
                        {{recent_thread.subject }}
                    {% else %}
                        No subject
                    {% endif %}
                </label>

                <label for="body">Message</label>
                <textarea name="body" id="body" value=""></textarea>

                <input type="submit" value="Send">
            </form>
        </div>


    {% endif %}

{% else %}

    <p>No message for this thread</p>

{% endif %}

</div>

Updated: Added the views.py

Views for displaying the message.

@login_required(login_url='/accounts/required_login/')
def message(request):
    user = request.user

    # Get all the threads of that user
    threads = user.thread_set.all()

    # Order the threads by which thread recieved the latest message
    order_threads_message = threads.annotate(max_sent_date=Max('message__sent_date')).order_by('-max_sent_date')

    if order_threads_message.count() > 0:
        # Get the recent thread
        recent_thread = order_threads_message[0]

        if recent_thread.message_set.all().count() > 0:

            # Get the conversations of the recent thread
            recent_thread_conversations = recent_thread.message_set.all()

            return render(request, 'conversations.html', {
                'recent_thread':recent_thread,
                'all_threads':order_threads_message,
                'conversations':recent_thread_conversations,
                'active': recent_thread.id
                })
        else:
            recent_thread_conversations = 0

            return render(request, 'conversations.html', {
                'recent_thread':recent_thread,
                'all_threads':order_threads_message,
                'conversations':recent_thread_conversations,
                'active': recent_thread.id
                })

    else:
        order_threads_message = 0

        recent_thread_conversations = 0

        return render(request, 'conversations.html', {
            'all_threads':order_threads_message,
            'conversations':recent_thread_conversations,
            })

Answer №1

A convenient method is to iterate through the messages in a reverse sequence:

{% for chat in chats reversed %}
    ...
{% endfor %}

Answer №2

To achieve a "bottoms up" display, employ the #reverse() method with your QuerySet. Assume that the threads are arranged in reverse order, where the latest message comes first.

chat_messages.reverse()

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

Highlighting menu borders and images upon loading of the page

Currently, I am working on creating a unique menu design where the initial link is highlighted with a border-bottom when the page loads. Additionally, there is an image that follows the mouse when hovering over each link in the menu. Although I have succe ...

Locating an individual element using Selenide (Selenium) and the cssSelector method

If you have a structure of elements similar to the one shown in the image, it is possible to extract each static property using: $$('#static-information .value').get(0) or $$('.static-property .value').get(0) However, as each static p ...

Creating a sleek appearance for Bootstrap input within the selectize.js component by mimicking the input-sm

I am currently working with a selectize component that appears like this: https://i.sstatic.net/z2aTw.png My objective is to adjust the appearance of the search input to make it smaller by changing its class from the standard bootstrap input to input-sm. ...

Switch up the current Slick Carousel display by utilizing a div element

We have implemented the slick carousel to show only one slide at a time within the <div class='item__wrapper'>. Beneath this are three items, and we want the slick carousel to update when any of these items are clicked. Issues Using item ...

Transforming the style of a particular element within React using Array().fill().map's method

Looking for a way to dynamically change the color of an array in React + styled jsx? Let's say you want to change the color when the number of elements in the array is a multiple of 4 (e.g. the index is 4, 8, etc.) Is there a clever solution to achi ...

Generating JSON data from Dom elements within a specified `div` container

My goal is to extract all the elements from within a div element, which may consist of multiple inputs, checkboxes, radiobuttons etc. After that, I want to convert the id or name and value attributes into a format that can be read as JSON. I attempted to ...

Text box with no entry instead of displaying a zero value

Displayed below is a number text box. <input type="number" ng-model="item.TotalUnitsCompleted" /> The TotalUnitsCompleted model is of type int. How can I make the text box display a blank or empty value instead of 0? Currently, it shows as 0. Thank ...

Converting MySQL data into a CSV file using HTML tags

My current task involves exporting a mysql table to a CSV file. The table structure includes the following columns: id, name, title, content Within the content column, there is HTML code that is causing line breaks when trying to open the exported file d ...

Trouble with placing an absolutely positioned element using Tailwindcss

I am currently working on a project using TailwindCSS in which I have a logo positioned to the left and navigation to the right. Both elements are centered, but because the logo has a position of absolute, it appears in front of the navigation. I would lik ...

Tips for incorporating scrollbars into a full screen web application's content area that spans the entire height of the screen with CSS

I am currently working on a full screen web app. I have applied CSS 100% height to the HTML, body, and parent elements. Within the app, there is a contents table that dynamically grows as items are added to it. My goal is to have a vertical scrollbar autom ...

Steps for clearing the UIWebView application cache for HTML5 applications

I recently encountered a problem where the HTML5 application cache stopped working in a native container using UIWebView to display HTML content. The cache.manifest file was updated, and UIWebView started downloading the process but failed at a specific ...

Querying data objects in Django for a specific list item

As a Django beginner, I've encountered a problem that has me stumped despite my efforts to find a solution online. Here's the model I'm working with, called movieTitles: class movieTitle(models.Model): title = models.Charfield(max_lengt ...

Empty array returned when using wrapper.classes() with Vue-test-utils and CSS modules

Recently I started using Vue Test Utils along with CSS Modules. My Vue component is all set up with CSS Modules and it functions perfectly in the app as well as in Storybook. Take my BasicButton for example: <template> <button :class="[ ...

Is it possible to have <a> function as <input type="image" />?

Our web application is currently undergoing some updates to the messaging functionality for communicating with other members. As part of this process, I need to replace certain elements: <input type="image" name="cancel" src="/rpc/button/?text=Cancel" ...

Send back the HTML content following an AJAX POST request

Utilizing an ajax call to submit a form and create an object. After the object is successfully created in the views, I am using the object instance to render a template called footemplate. My goal is for footemplate to be dynamically inserted into my curr ...

What is the best way to add a -webkit-transform to a div without affecting its enclosed elements?

Is there a way to apply a webkit transformation to a div without affecting the text inside? I need help with achieving this. Below is my current code: .main_div { width:200px; height:100px; background:red; margin-left:55p ...

Guide on sending the name of a JSON file to a JavaScript function when a button is clicked

My dilemma currently involves a JavaScript file that generates HTML content based on the data stored in JSON files. In my "Resources" folder, I have a collection of JSON files along with an HTML file containing various buttons. To illustrate, consider the ...

The JQuery code restricts the use of multiple buttons within a single instance

UPDATE I am facing an issue where I am trying to add the same set of buttons inside multiple divs, however, it seems that the button set only appears in one div at a time. I want the button set to show up in every location where I place it. Here is the co ...

jQuery event triggers upon completion of execution

A custom code has been integrated into my project using jQuery. Check out the code snippet below: <script> $("#startProgressTimer").click(function() { $("#progressTimer").progressTimer({ timeLimit: $("#restTime").val(), onFinish ...

ag-Grid incorporating new style elements

For my Angular application, I have a simple requirement of adding a CSS class when a row expands or collapses to highlight the row. I attempted to use gridOptions.getRowClass following the documentation at https://www.ag-grid.com/javascript-grid-row-styles ...