Django+ajax implementing an online chat room

Source: Internet
Author: User

Django+ajax implementing an online chat room

One of the small projects is a simple chat room
Demand:

    • To speak after registering for the login
    • Initial display of recent messages in a chat box
    • Sending messages using AJAX to complete the storage of messages in the background
    • Use round robin to constantly request get new messages to appear 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):        returnu‘%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%}<h4 class="list-group-item-heading">        {{Chat.sender}}:{{chat.content}} </h4><p class="List-group-item-text">         {{Chat.time}} </P><input type="Hidden" class="Chat_ ID " value="          {{chat.id}}  "/><br>                 {% endfor %} </div></div><!--form--<form id="Chatform" class="form-horizontal panel Container" method= "POST" Action="." >     {% csrf_token %}    <div class="Form-group col-md-10">        <textarea type= "text" name="Content" id="Content " value=" " class=" Form-control " id=" Examplemessage "  Placeholder=""></textarea>    </div>    <div class="Form-group col-md-4">        <input type="hidden" name="Post_type" value=" Send_chat "/>        <input type="Submit" class="btn btn-lg btn-primary" Value="Send"/>    </div></form>{% endblock %}
Js
{% block script%}<script>$( function() {Updatemsg ();//Finer Information            //Form Submit Event$("#chatForm"). Submit ( function() {          //ajax submitting a form$.post ("./post/",              $(' #chatForm '). Serialize (), function(data) {$("#content"). Val ("");//Clear content box After message is sent successfully});return false;//block form submission}); });//Update 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 ()", +);//Update once per second}</script>{% endblock %}

JS part of the main has two, one is to send messages, one is round-robin receive
Send the message part: Post the information in the Chatform form to the processing page, including the chat message content and Post_type, which is a variable of my own definition, used to handle different post requests on the same page address, where Post_type is Send_chat , the message is sent.
The part of the update message, the UPDATEMSG () function, uses the POST request to post data to the same address, including post_type:get_chat,last_chat_id: This is the ID of the last chat message obtained from the chat box, $(".chat_id").last().val() This is to ensure that the information is the last message after the chat information, and finally set the cycle time of one second, and constantly execute.

Views
 def index(Request):Chats = List (Chat.objects.all ()) [- -:]returnRender (Request,' chatroom.html ', {' Chats ': Chats})@csrf_exempt def post(Request):    ifRequest.method = =' POST ': Post_type = Request. Post.get (' Post_type ')ifPost_type = =' Send_chat ': New_chat = Chat.objects.create (content = Request. Post.get (' content '), sender = Request.user,) new_chat.save ()returnHttpResponse ()elifPost_type = =' Get_chat ': last_chat_id = Int (request. Post.get (' last_chat_id '))#print last_chat_idChats = Chat.objects.filter (id__gt = last_chat_id)returnRender (Request,' chat_list.html ', {' Chats ': Chats})Else:RaiseHttp404
    • The index () function handles the main chat interface and queries the last 100 chat messages in the database to display in the chat box
    • The post () function processes the received Chat message request and determines the processing action according to the Post_type
      • Send_chat: Generate a new chat instance stored in the database, here can not return anything, because the chat message polling speed is fast, itself is constantly updating the message.
      • Get_chat: Get last_chat_id First, then use chats = Chat.objects.filter(id__gt = last_chat_id) this sentence to get the ID of all chat instances after last_chat_id, where filter (id__gt = last_chat_id) The filter ID is greater than the LAST_CHAT_ID object.

Completed ~

URL Stamp here

Full Project GitHub Address

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Django+ajax implementing an online chat room

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.