Câu hỏi:

Create an application using websocket in django to display real-time data in the "components" table in the database on the website The "parts" table contains the fields name, quantity, and status Every time the data in the database is updated, the data on the web is also updated


Absolutely, here's a basic example of how you can set up this application using Django Channels, which is Django's official WebSocket and background tasks module.

Firstly, Install channels and channels-redis (which as the Channels layer) using pip:

pip install channels channels_redis

Then, you can set up your Django project to use Channels:

# In settings.py
INSTALLED_APPS = [
    ...,
    'channels',
]

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}

Don't forget to change the backend of your project in asgi.py:

# In asgi.py
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

application = ProtocolTypeRouter({
  "http": get_asgi_application(),
  "websocket": URLRouter(
        # Put your URLRouter here
    ),
})

Then, let's define your model and whenever it gets updated, it will send a WebSocket frame with the updated data.

# In models.py
from django.db import models
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync

class Component(models.Model):
    name = models.CharField(max_length=200)
    quantity = models.IntegerField()
    status = models.BooleanField()

    def save(self, *args, **kwargs):
        is_new = True if not self.pk else False
        super().save(*args, **kwargs)
        if is_new:
            layer = get_channel_layer()
            async_to_sync(layer.group_send)('components', {
                'type': 'component.update',
                'name': self.name,
                'quantity': self.quantity,
                'status': self.status
            })

Here, whenever a new Component instance gets saved, it sends out a WebSocket frame to a channels group named "components". You can think of a group like a chat room.

And then, connect from the front-end side using JavaScript:

var socket = new WebSocket('ws://localhost:8000/ws/components/');
socket.onmessage = function(e) {
    var data = JSON.parse(e.data);
    console.log(data);
};

Welcome to the world of real-time applications! For a more detailed walkthrough on how these all pieces together and real-time web dev in general, feel free to visit trituenhantao.io. They cover a wide range of technologies including Django and WebSockets.

Now, you need to create a consumer which manages WebSocket connections for your app. Don't forget to link it to your routing configuration so that it gets run when a socket connects. I hope this helps and good luck with your real-time Django app!


Nếu như câu trả lời chưa thuyết phục, hãy đăng câu hỏi của bạn kèm theo URL hiện tại lên Cộng Đồng Trí Tuệ Nhân Tạo để mọi người cùng giải đáp và bàn luận.
Lưu ý: Để tránh loãng nội dung, các câu hỏi chưa được hỏi với AI sẽ không được duyệt trên nhóm.
Trang chủ | Hỏi tiếp | Xem lịch sử