Django + ajax implements online chat rooms, djangoajax
Django + ajax online chat room
One of the small projects is a simple chat room.
Requirements:
- Registration and login before speaking
- Displays the most recent message in the chat box.
- Use ajax to store messages in the background.
- Use Round Robin to request new get messages to be displayed in the chat box
Models
Design the structure of the chat message topic:
class Chat(models.Model): sender = models.ForeignKey(User, related_name='has_chats') content = models.TextField() time = models.DateTimeField(auto_now_add=True, null=True) def __unicode__(self): return u'%s' % self.content
Templates
{% Extends "base.html" % }{% block title %} chat room {% endblock % }{% block content %} <! -- Chat box --> <div class = "list-group col-md-10 col-md-offset-1 well"> <div class = "list-group-item" >{% for chat in chats %}
Js {% Block script %} <script >$ (function () {updateMsg (); // For more information // form submit event $ ("# chatForm "). submit (function () {// ajax submit form $. post (". /post/", $ ('# chatForm '). serialize (), function (data) {$ ("# content "). val (""); // clear the content box after the message is sent successfully}); return false; // prevent form submission}) ;}; // update the message function updateMsg () {$. post (". /post/", {post_type:" get_chat ", last_chat_id: $ (". chat_id "). last (). val ()}, function (data) {$ ('. list-group-item '). append (data); // parse the returned xml}); setTimeout ("updateMsg ()", 1000); // update once per second} </script >{% endblock %}
There are two main parts in js: one is to send messages, and the other is to receive round-robin messages.
Message sending: post the information in the chatForm form to the processing page, including the chat information content and post_type. This is a variable defined by myself, it is used to process the tags of different post requests at the same page address. Here, post_type is send_chat, that is, to send messages.
Update the message. The updateMsg () function uses the post request to post data to the same address. The content includes post_type: get_chat, last_chat_id: this is the id of the last chat information obtained from the chat box,$(".chat_id").last().val()
This is to ensure that the information after the last chat information is obtained, and the loop time is set to one second for continuous execution.
Views def index(request): chats = list(Chat.objects.all())[-100:] return render(request, 'chatroom.html', {'chats': chats})@csrf_exemptdef post(request): if request.method == 'POST': post_type = request.POST.get('post_type') if post_type == 'send_chat': new_chat = Chat.objects.create( content = request.POST.get('content'), sender = request.user, ) new_chat.save() return HttpResponse() elif post_type == 'get_chat': last_chat_id = int(request.POST.get('last_chat_id')) #print last_chat_id chats = Chat.objects.filter(id__gt = last_chat_id) return render(request, 'chat_list.html', {'chats': chats}) else: raise Http404
- The index () function is used to process the chat main interface. The last 100 chat messages in the database are displayed in the chat box.
- The post () function processes the received chat message requests and determines the processing action based on post_type.
- Send_chat: generates a new Chat instance and stores it in the database. Nothing can be returned here, because the polling speed of Chat messages is fast and messages are constantly updated.
- Get_chat: first obtain the last_chat_id, and then use
chats = Chat.objects.filter(id__gt = last_chat_id)
Obtain all Chat instances whose IDs are after last_chat_id.Filter (id _ gt = last_chat_id)It means to filter objects whose IDs are greater than last_chat_id.
Finished ~
URL stamp here
Github address of the complete project
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.