How to arrange messages in a chat box using Bootstrap 4 without the need for JavaScript

Is there a way to adjust my chat box so that messages appear at the bottom, like in any chat app? I am currently using Django and Bootstrap 4, here is the code I have:

                            <div class="list-group flex-column-reverse " id="Chatting" style="transform: rotate(-180deg);">

{% for message in object.messages.all %}

    <a class="list-group-item list-group-item-action border-white "  {% if message.user == user  %} style="background-color: rgba(190,229,235,0.1);"{% endif %}>
        <div class="row text-lowercase" style="height: 15px;">
        <div class="col text-left">
            <p style="font-size: 10px;">{{ message.user.first_name }} {{ message.user.last_name|slice:":1" }}</p>
        </div>
        <div class="col">
            <p class="text-right" style="font-size: 10px;">{{ message.date|date:"SHORT_DATETIME_FORMAT" }}</p>
        </div>
        </div><span>

        {{ message.text|linebreaks }}
        {% if message.attachment %}
            <img src="{{ message.attachment.url }}" width="50%"  ></img>
        {% endif %}
    </span>
    </a>


{% endfor %}

The id list of name has overflow: auto on it. If I use the code without The rotation part and without flex-column-reverse, the list of messages begin from the top of the box, which is counter-intuitive. If I use only flex-column-reverse I get the ordering correct but when the page loads it loads with the oldest message and the user has to scroll down, it also means everytime he writes a message he has to scroll down again. The hack that I am using works by showing the order correct and the page loads at the last message, however the scroll bar is at the left of the chat box and works in reverse with the mouse scroll. I added the ending screenshot. Is there any solution without using javascript? I am really horrible in comprehending javascript :÷ https://i.sstatic.net/CNnNu.png

Answer №1

In order to organize the messages in the desired order, I recommend making adjustments in the view rather than the template. If you are using class-based views, one approach would be to override the get_context_data method to include the messages in the desired sorting:

def get_context_data(self, **kwargs):
    context = super(). get_context_data(**kwargs)
    # Include messages sorted by date in ascending order
    # Assuming you are using a DetailView or similar with an 'object' field
    context['messages'] = self.object.messages.order_by('date')

    return context

When working with the template, iterate directly over the messages variable rather than object.messages.all.

If the messages typically need to be displayed in the specified order, consider adding this sorting rule to the Meta class ordering attribute of the Message model like so:

class Message(Model):
    # Define your model fields

    class Meta:
        ordering = ['date']

Based on your recent comment, it may be beneficial to iterate over the list in reverse order (refer to this documentation). In summary, the iteration process should be:

{% for message in obj.messages.all reversed %}
    <!-- Customize the rendering of your messages here --!>
{% endfor %}

To maintain a scroll-down effect, consider implementing a JS or CSS solution. For helpful insights, you can explore resources such as this related question.

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

Concealing the side navigation menu with HTML and CSS

Hey there, I'm trying to make my navbar automatically hide when the mouse is moved. I found an example that I want to use here. Despite reading some online documentation, I just can't seem to figure out how to do it. Here's a snippet of my c ...

The expect.objectContaining() function in Jest does not work properly when used in expect.toHaveBeenCalled()

Currently, I am working on writing a test to validate code that interacts with AWS DynamoDB using aws-sdk. Despite following a similar scenario outlined in the official documentation (https://jestjs.io/docs/en/expect#expectobjectcontainingobject), my asser ...

Updating div visibility based on form content in PHP

I am struggling to find a way to filter a page filled with divs based on form input to determine whether they should be displayed or not. The layout is akin to a collection of articles, where each div showcases an image and some text that links to the comp ...

How to pass a JSON object to a component's constructor in Angular 2

In a unique situation, my primary component config.editor.component performs extensive processing and generates various JSON objects. I am content with this approach. The template for this component then proceeds to render another component - api.entry.com ...

How can I display the value entered in a text input field when using ajax upload?

Is there a way to display the value of an input type text when using ajax for file upload? I have successfully implemented code to upload files to a directory called attachments_files, but I am facing an issue. How can I retrieve and echo the value from i ...

When the add button is clicked, I would like to implement a feature where a checkbox is added

When the user clicks on the link "출력하기", I want the web page to add a checkbox to all images. I wrote this code, but it's not working. Can anyone help me? This is my JS: $(document).ready(function(){ $("#print").on('click', fu ...

Converting string literals to an array of enums

I have a scenario where I am getting the following data in an API response: { "roles": [ "ADMIN", "USER" ] } The response always includes an array of roles (USER, PRESENTER, ORGANIZER, and ADMIN). I am looking to transform this into a valid TypeScript a ...

How to pass selected rows from Material-Table in React.js to another page

Is there a way to redirect to another page while passing selected row data as a prop? I am using material-table and I need to transfer the selected rows data to another page upon clicking the "Export" button, so that I can utilize the data in generating a ...

Retrieve the current font style with Kendo UI Editor

Recently, I've been facing some challenges while working with the Kendo UI Editor. Specifically, I'm struggling to retrieve the current font style. My goal is to use JavaScript or jQuery to obtain the following values: Values I am looking for: ...

Is there a way to create a more user-friendly header in Django's StackedInline for a through model that is

Currently, I am using a Django admin StackedInline setup like this: class BookInline(admin.StackedInline): model = Book.subject.through    verbose_name = 'Book' verbose_name_plural = 'Books associated with this subject' cla ...

The Input Boxes Are Too Broad

Currently, I am working on a responsive web page that features a form. However, I have noticed that all the input elements are spilling out of the form both from the left and right sides. Can someone please shed some light on why this could be happening? ...

A clever method for implementing lazy-loading using mobx

Can you provide guidance on the most effective way to lazy load properties with MobX? I've been grappling with this issue for a few days now, and I've struggled to find suitable examples ever since strict mode was introduced. While I appreciate ...

JavaScript Promise Fundamentals

While I am quite familiar with coding in JavaScript, the benefits of promises in the JS world still seem somewhat unclear to me. Below is an example of asynchronous calls using callbacks nested within each other. (function doWorkOldSchool() { setTime ...

use jquery to dynamically switch CSS class on navigation with animated arrows

Looking to update arrows to display a right arrow when the parent list item has the .active class. Here is the jQuery code: jQuery(function(){ initAccordion(); }); function initAccordion() { jQuery('.accordion').slideAccordion({ opener ...

How to manage form submissions in Vue.js using inputs within child components

I'm working on a parent component that acts as a form. This form consists of multiple child components, each containing input fields. <template> <div class="form"> <generalData v-model="input" /> <textAreas v- ...

Transferring information using "this.$router.push" in Vue.js

I'm currently developing a restaurant review project using Django REST and Vue.js. To ensure uniqueness, I have adopted Google Place ID as the primary key for my restaurants. The project also incorporates Google Place Autocomplete functionality. The ...

Leveraging the Power of Ajax Button for Django Model Filtering

My goal is to create buttons on my website that, once clicked, trigger a specific filter on my database of models. Specifically, I am trying to sort the "Clothes_Item" model and apply various filters. To start off, I want to keep it simple and create a but ...

Prevent the browser from autofilling password information in a React Material UI textfield when it is in focus

I am currently utilizing React Material UI 4 and I am looking to disable the browser autofill/auto complete suggestion when focusing on my password field generated from `TextField`. Although it works for username and email, I am encountering issues with d ...

Issue with implementing jQuery tab functionality

I'm just starting to learn JS, HTML, and CSS, and I could use some guidance on setting up jQuery tabs. Currently, I'm encountering an error that says "Uncaught TypeError: $(...).tabs is not a function". Any help would be greatly appreciated. Than ...

Tips for sorting Django objects to retrieve the top X items with the highest property values

Hey there, I'm facing a challenge with a class known as Hero, which contains 150 objects. Each object in this class has a property called Winrate. My goal is to extract the top 12 heroes based on their win rates. class Hero(models.Model): hero_n ...