Skip to content
Advertisement

how to get messages (data) in real time from database using ajax and django

i want to get messages in realtime using ajax and django for the backend, i have written the logic to send the messages and that is working, but i want to get a message immediately another user sends me a message without having to refresh the page, i tried using ajax interval but it seem i am not getting a hang of how to properly use the interval and forloop in ajax, what is it that i should do to achive the result i want?

Updated With Image how to append the messages with the profile picture, full name from profile model and date when message was sent. enter image description here

Advertisement

Answer

Well, I understand what you are trying to achieve. You are trying to make a chat system using django and you are using ajax for the thing. But the thing is ajax is mostly used for making asynchronous requests and for the api requests and ajax just uses http requests for the data transfer . You want a two way and long running connection for the chat system .

What you are doing can easily be done via django channels and django asynchronous ( asgi.py more specifically ) .

Django channels are great for creating real time systems ( chat , notification , etc) .

Go to this [link][1] for learning about django channels and making your own chat system . And also I have my own chat system in my github. Just clone [this][2] repository . Run the terminal in this folder and ( pip install -r requirements.txt ) install the requirements ( better use virtual environment ) and then just run the server for the file . You will get the chat system totally working.

If you want to send image via json data or an api . You have to convert it to utf-8 format using base64 encoder .

The code

# you get the image , say image = instance.profile.image (var image)

# in your consumers.py ( or views.py )
import base64

coneverted_image = base64.b64encode(instance.profile.image.read()).decode("utf-8")

In your html

<!-- js file ( where you get the data -->
image = json_data.image()


<!-- in html append your data  in chat system -->

<img src = json_data.image>

This will do your work. [1]: https://channels.readthedocs.io/en/latest/tutorial/part_1.html [2]: https://github.com/omkashyap007/RealTimeChatApp

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement