SoFunction
Updated on 2024-11-15

Python using django framework to implement multi-people online anonymous chat applet

Recently, I saw a lot of design websites, are provided with a number of online anonymous chat small features, feel very interesting, so based on python's django framework to write their own, support for manual real-time name change, the bottom provides a complete source code.

Online chat address (no login required, one window for one user).

/chatroom/happy/

Mobile chat rendering.

Web Chat rendering.

Ideas for implementation.

Sent messages are first written to the database through ajax, and the messages written to the database are displayed to the front-end interface through ajax's circular request.

Front-end core code.

<script>
 $(function () {
  $("#send").click(function () {
   var input_info = $("#input_info").val();
   if (input_info.length < 1) {
    alert("Please enter characters to send.");
    return;
   } else if (input_info.length > 200) {
    alert("You can't send more than 200 characters at a time haha~");
    return;
   }
   else {
    // Get the value of the csrftoken
    var csrf_value = $('#csrfmiddlewaretoken').text();
    var user_id = $("#user_id").text();
    var user_name = $("#user_name").text();
    $.ajax({
     'url': '/chatroom/save_chat_log/',
     'data': {
      'chat_content': input_info,
      'user_id': user_id,
      'user_name': user_name,
      'user_ip': '127.127.127.127',
      'csrfmiddlewaretoken': csrf_value
     },
     'type': 'post',
     'async': false,
     'success': function (data) {
     }
    });
    $("#input_info").val("");
    ($("#show_info").scrollTop());
   }
  })
 })
</script>
<script>
 var user_id = $("#user_id").text();
 var user_name = $("#user_name").text();
 $(function () {
  var last_id = 0;
  var csrf_value2 = $('#csrfmiddlewaretoken').text();
  function update_info() {
   // ajax get latest data
   $.ajax({
    'url': '/chatroom/get_near_log/',
    'data':{"last_id":last_id,'csrfmiddlewaretoken': csrf_value2},
    'type':'post',
    'async': false,
    'success':function (data) {
     if (parseInt(last_id) == parseInt(().last_id)){
      return;
     }
     // Get the id value from the backend and store it in a global variable.
     last_id = ().last_id;
     // Read the contents and print them.
     content = ().info;
     for (var i=0; i< ; i++){
      if (parseInt(content[i].user_id) == parseInt($("#user_id").text())){
       var html = "<div class='my_info'><span>"+content[i].user_name+"</span></div>";
       html = html + "<div class='my_one_info'>"+content[i].mess+"</div>";
       $("#content").append(html);
      }else{
       var html = "<div class='other_info'><span>"+content[i].user_name+"</span></div>";
       html = html + "<div class='other_one_info'>"+content[i].mess+"</div>";
       $("#content").append(html);
      }
      $("#show_info").scrollTop($("#content").height())
     }
    }
   })
  }
  update_info();
  setInterval(update_info, 1000);
 })
</script>
<script>
 $(function () {
  //Listen for keyboard clicks
  $(document).keyup(function (event) {
   if ( == 13){
    $("#send").click();
   }
  })
 })
</script>
<script>
 $(function () {
  $("#change_name").click(function () {
   // Get a new name
   var new_name = String($("#new_name").val());
   // Check if the new name is legal
   // If legal
   if (new_name.length<11 && new_name.length>0){
    (new_name);
    $("#user_name").text(new_name);
    $("#new_name").val("")
   }else{
    alert("Nickname length should be 1-10, please re-enter.");
    $("#new_name").val("")
   }
  })
 })
</script>
<div >
 <div class="my_nike_name">My nickname.:<span >{{user_name}}</span><span><button >rename</button><input type="text" ></span></div>
 <div >
  <div >
  </div>
 </div>
 <br>
 <div class="my_nike_name">messages</div>
 <input type="text" >
 <button >发送messages</button>
 <div  style="display: none">{{user_id}}</div>
 <div  style="display: none">{{user_ip}}</div>
 <span id ="csrfmiddlewaretoken" style="display: none">{{csrf_token}}</span>
</div>

Backend core code.

# Return to base page
def happy(request):
 user_info = UserInfo()
 # Initial username is anonymous
 user_name = "Anonymous user"
 user_info.user_name = user_name
 # Utilize time to generate temporary IDs
 user_id = int(())
 user_info.user_id = user_id
 # Get user ip
 user_ip = wrappers.get_client_ip(request)
 user_info.user_ip = user_ip
 user_info.save()
 return render(request, 'chatroom/', locals())
# Save the chat
def save_chat_log(request):
 try:
  print("Backend received ajax message.")
  chatinfo = ChatInfo()
  # Get the data passed from the front-end
  chat_content = (request, "chat_content")
  user_ip = wrappers.get_client_ip(request)
  user_name = (request, "user_name")
  user_id = (request, "user_id")
  # Data to be deposited in the database
  chatinfo.chat_content = chat_content
  chatinfo.user_ip = user_ip
  chatinfo.user_name = user_name
  chatinfo.user_id = user_id
  ()
  return JsonResponse({"ret":0})
 except:
  return JsonResponse({"ret":"There was a problem with the save."})
  pass
# Get recent chat messages
def get_near_log(request):
 try:
  # Get all the information in the database
  all_info = ()
  # Get the id of the last message in the database
  id_max =(Max('id'))
  last_id = id_max["id__max"]
  # print("The latest id in the backend database is ", last_id)
  # Get the id value of the request
  old_last_id = (request, "last_id")
  print(old_last_id,"<-<-")
  print(old_last_id, type(old_last_id),"-->")
  # print("The id sent from the backend is ",old_last_id)
  # Dictionary of returned information, return the current time (current_date), return the list of information (id_info)
  # If requested for the first time, reply with the id of the last message.
  if int(old_last_id) == 0:
   user_ip = wrappers.get_client_ip(request)
   result_dict = dict()
   result_dict["last_id"] = last_id
   result_dict["info"] = [{"id":"-->", "mess":"Welcome."+user_ip+"Come to the chat room!", "user_name":"System Message:"}]
   result_dict["user_id"] = ""
   result_dict = (result_dict,ensure_ascii=False)
   # print("First handshake")
   return JsonResponse({"data":result_dict})
  # If no messages are updated within the data
  elif int(old_last_id) >= int(last_id):
   result_dict = dict()
   result_dict["last_id"] = last_id
   result_dict["info"] = [{last_id:"Welcome to the chat room again!"}]
   result_dict["user_id"] = ""
   result_dict = (result_dict,ensure_ascii=False)
   # print("One interaction without updates")
   return JsonResponse({"data":result_dict})
  # If there's a message to update
  else:
   # print("There are updated replies")
   result_dict = dict()
   # Get a new collection of message objects
   the_new_info =(id__gt=old_last_id)
   # Create message lists
   mess_list = list()
   # Compose a dictionary of the latest messages for return
   for info in the_new_info:
    # print(info)
    # print ("-->",info.chat_content, )
    # Create a message dictionary
    mess_dic = dict()
    mess_dic["id"] = 
    mess_dic["mess"] = info.chat_content
    # Add the user the message belongs to to the message list
    mess_dic["user_name"] = info.user_name
    mess_dic["user_id"] = info.user_id
    # Add the message dictionary to the message list
    mess_list.append(mess_dic)
  result_dict["last_id"] = last_id
  result_dict["info"] = mess_list
  # result_dict["info"] = [{"id":3, "mess":"hahah"}, {"id":4, "mess":"666"}]
  result_dict = (result_dict,ensure_ascii=False)
  # print("--->>>", type(result_dict))
  return JsonResponse({"data":result_dict})
 except:
  return JsonResponse({"ret":"There's a problem with the refresh."})
  pass

summarize

The above is a small introduction to the Python using django framework to achieve multi-person online anonymous chat small program, I hope to help you, if you have any questions please leave me a message, I will reply to you in a timely manner. I would also like to thank you very much for your support of my website!