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?
directs.html
<div >
{% for direct in directs %} {% if direct.sender == request.user %}
<div >
<div>
<a href=""><img src="{{ direct.sender.profile.image.url }}" alt="img" width="40" height="40" /></a>
<div style="font-size: 10px; color: rgba(180, 180, 180, 0);"><p style="font-size: 10px; color: black;">{{direct.date|timesince}} ago</p></div>
</div>
<div >
<!-- <div >Sharon Lessman</div> -->
{{direct.body}}
</div>
</div>
{% else %}
<div >
<div>
<a href=""><img src="{{ direct.sender.profile.image.url }}" alt="img" width="40" height="40" /></a>
<div style="font-size: 10px; color: rgba(180, 180, 180, 0);"><p style="font-size: 10px; color: black;">{{direct.date|timesince}} ago</p></div>
</div>
<div >
<!-- <div >Sharon Lessman</div> -->
{{direct.body}}
</div>
</div>
{% endif %} {% endfor %}
</div>
<script>
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "GET",
url: "",
success: function (response) {
console.log("Sending");
for (var key in response.directs) {
let _html =
'<div >\
<div>\
<a href=""><img src="{{ request.user.profile.image.url }}" alt="img" width="40" height="40"></a>\
<div style="font-size:10px; color: rgba(180, 180, 180, 0);"><p style="font-size:10px; color: black;">{{direct.date|date:"d M, Y"}}</p></div>\
</div>\
<div >\
<!-- <div >Sharon Lessman</div> -->\
' response.directs[key].body "\
</div>\
</div>\
";
$(".chat-wrapper").append(_html);
}
},
});
}, 10000);
});
</script>
<!-- Sending message function and ajax logic -->
<div >
<form id="chat-form">
{% csrf_token %}
<div >
<input type="hidden" name="to_user" id="to_user" value="{{active_direct}}" />
<input name="body" id="body" type="text" placeholder="Type your message" required />
<button type="submit">Send</button>
</div>
</form>
<script type="text/javascript">
$(document).on("submit", "#chat-form", function (e) {
e.preventDefault();
let _body = $("#body").val();
let _to_user = $("#to_user").val();
$.ajax({
type: "POST",
url: "{% url 'send-directs' %}",
data: {
body: _body,
to_user: _to_user,
csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(),
},
success: function (data) {
console.log("working");
let _html =
'<div >\
<div>\
<a href=""><img src="{{ request.user.profile.image.url }}" alt="img" width="40" height="40"></a>\
<div style="font-size:10px; color: rgba(180, 180, 180, 0);"><p style="font-size:10px; color: black;">{{direct.date|date:"d M, Y"}}</p></div>\
\
</div>\
<div >\
<!-- <div >Sharon Lessman</div> -->\
' _body "\
</div>\
</div>\
";
$(".chat-wrapper").append(_html);
},
});
document.getElementById("body").value = "";
});
</script>
</div>
views.py
@login_required
def Directs(request, username):
user = request.user
messages = Message.get_message(user=user)
active_direct = username
directs = Message.objects.filter(user=user, reciepient__username=username)
directs.update(is_read=True)
for message in messages:
if message['user'].username == username:
message['unread'] = 0
context = {
'directs': directs,
'messages': messages,
'active_direct': active_direct,
}
return render(request, 'directs/direct.html', context)
def SendDirect(request):
if request.method == "POST":
from_user = request.user
to_user_username = request.POST['to_user']
body = request.POST['body']
to_user = User.objects.get(username=to_user_username)
Message.sender_message(from_user, to_user, body)
# return redirect('message')
success = "Message Sent."
return HttpResponse(success)
CodePudding user response:
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 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 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.