Home >Backend Development >PHP Tutorial >How to write the online chat function of CMS system in Python
How to use Python to write the online chat function of the CMS system
With the continuous development of information technology, instant messaging has been widely used in various fields. Adding an online chat function to the CMS system can help website administrators and users communicate better. This article will introduce how to use Python to write the online chat function of a CMS system, with code examples.
First, we need to choose a suitable Python framework. In this example, we will use the Django framework. Django is a popular web development framework that provides many powerful tools and functions to facilitate us to create a complete CMS system. If you don't have Django installed yet, install it first.
After installing Django, we start to create a new Django project. Open a command line window and enter the following command:
django-admin startproject chat_cms
This will create a new project named chat_cms in the current directory. Next, we go into the project directory and create an application:
cd chat_cms python manage.py startapp chat
Next, we need to define the model to store chat messages. In the chat application's models.py file, enter the following code:
from django.db import models from django.contrib.auth.models import User class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sent_messages') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='received_messages') content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True)
This model defines a message class that has a sender, a receiver, content, and timestamp. Sent and received messages can be easily accessed in the User model using the related_name parameter.
Next, we need to create the corresponding view function in Django. In the views.py file of the chat application, enter the following code:
from django.shortcuts import render, get_object_or_404 from django.contrib.auth.decorators import login_required from chat.models import Message @login_required def chat_view(request, receiver_id): receiver = get_object_or_404(User, id=receiver_id) if request.method == 'POST': content = request.POST['content'] message = Message(sender=request.user, receiver=receiver, content=content) message.save() messages = Message.objects.filter(sender=request.user, receiver=receiver) | Message.objects.filter(sender=receiver, receiver=request.user) return render(request, 'chat/chat.html', {'receiver': receiver, 'messages': messages}) @login_required def contact_list_view(request): contacts = User.objects.exclude(id=request.user.id) return render(request, 'chat/contact_list.html', {'contacts': contacts})
This view function chat_view is responsible for displaying and processing the chat interface with a certain user, and requires login to access. It will get the sender's ID from the URL and then find the corresponding user based on the ID. If the request method is POST, it means that the user has sent a new message and we will save it to the database. Finally, all messages related to these two users are passed to the template for display.
Another view function contact_list_view is responsible for displaying the current user's contact list and also requires logging in to access. It will exclude the current user itself and pass all other users to the template.
Next, we need to define the URL route to map the view function. In the urls.py file of the chat application, enter the following code:
from django.urls import path from chat import views app_name = 'chat' urlpatterns = [ path('chat/<int:receiver_id>/', views.chat_view, name='chat'), path('contact-list/', views.contact_list_view, name='contact_list'), ]
The above defines two URL routes, corresponding to the two view functions mentioned above. Among them, c9f6b0e14d05317692e4d9e16d90c0b0
indicates receiving an integer type parameter as the receiver's ID.
Finally, we need to create templates to display the chat interface and contact list. In the templates/chat directory of the chat application, create two template files, chat.html and contact_list.html, and enter the following codes respectively:
chat.html:
{% extends 'base.html' %} {% block content %} <h1>Chat with {{ receiver.username }}</h1> <div id="messages"> {% for message in messages %} <p>{{ message.timestamp }} - {{ message.sender.username }}: {{ message.content }}</p> {% endfor %} </div> <form method="post" action="{% url 'chat:chat' receiver.id %}"> {% csrf_token %} <input type="text" name="content" required> <button type="submit">Send</button> </form> {% endblock %}
contact_list.html:
{% extends 'base.html' %} {% block content %} <h1>Contact List</h1> <ul> {% for contact in contacts %} <li><a href="{% url 'chat:chat' contact.id %}">{{ contact.username }}</a></li> {% endfor %} </ul> {% endblock %}
The above templates show the HTML structure of the chat interface and contact list respectively, and use Django's template syntax to display messages and user information.
Finally, we need to modify the settings.py file of the project and add the chat application to the INSTALLED_APPS list:
INSTALLED_APPS = [ ... 'chat', ]
At this point, we have completed writing the online chat function of the CMS system in Python . Through the above steps, we created a Django project and defined the message model, view function, URL routing and template to implement online chat between users. You can further expand and improve according to actual needs.
I hope this article will be helpful to you, and I wish you good luck in writing the online chat function of the CMS system!
The above is the detailed content of How to write the online chat function of CMS system in Python. For more information, please follow other related articles on the PHP Chinese website!