django-如何在发送消息后显示用户的个人资料图片和消息?

7rfyedvj  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(384)

我有一个实时聊天应用程序,我正试图在用javascript发送消息后显示一个带有消息的个人资料图片。这是我的密码。。。
models.py-这是我的消息和配置文件模型

class Message(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    room = models.CharField(max_length = 255)
    content = models.TextField()
    date_added = models.DateTimeField(auto_now_add = True)

    class Meta:
        ordering = ('date_added', )

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.png', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, *args,**kwargs):
        super().save(*args,**kwargs)

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

消费者.py

class ChatRoomConsumer(AsyncWebsocketConsumer):
async def connect(self):
    self.room_name = self.scope['url_route']['kwargs']['room_name']
    self.room_group_name = 'chat_%s' % self.room_name
    print(self.room_group_name)

    await self.channel_layer.group_add(
        self.room_group_name,
        self.channel_name
    )

    await self.accept()

async def disconnect(self, close_code):
    await self.channel_layer.group_discard(
        self.room_group_name,
        self.channel_name
    )

async def receive(self, text_data):
    text_data_json = json.loads(text_data)
    message = text_data_json['message']
    username = text_data_json['username']
    room = text_data_json['room']

    await self.save_message(username, room, message)

    await self.channel_layer.group_send(
        self.room_group_name,
        {
            'type': 'chatroom_message',
            'message': message,
            'username': username,
        }
    )

async def chatroom_message(self, event):
    message = event['message']
    username = event['username']

    await self.send(text_data=json.dumps({
        'message': message,
        'username': username,
    }))

@sync_to_async
def save_message(self, username, room, message):
    user = User.objects.get(username = username)
    Message.objects.create(author = user, room = room, content = message)

pass

下面是实时聊天的javascript代码。。。

{{ request.user.username|json_script:"user_username" }}
{{ room_name|json_script:"room-name" }}
<script>
    const user_username = JSON.parse(document.getElementById('user_username').textContent);
    document.querySelector('#submit').onclick = function (e) {
        const messageInputDom = document.querySelector('#input');
        const message = messageInputDom.value;
        if(message.trim() == ''){
        }
        else {
            chatSocket.send(JSON.stringify({
            'message': message,
            'username': user_username,
            'room': roomName,
        }));
        messageInputDom.value = '';
        }
    };
    const roomName = JSON.parse(document.getElementById('room-name').textContent);

    const chatSocket = new WebSocket(
        'ws://' +
        window.location.host +
        '/ws/chat/' +
        roomName +
        '/'
    );

    chatSocket.onmessage = function (e) {
        const data = JSON.parse(e.data);
        console.log(data)
        if (data.message) {
                document.querySelector('#chat-text').innerHTML += ('<img id="imageid" src="{{ message.author.profile.image.url }}">' + data.username + '<br>' + data.message + '<br>');
            }
        else {

        }
    }
</script>

问题在于这个 <img id="imageid" src="{{ message.author.profile.image.url }}"> 在javascript代码中。因此,我的问题是,在发送消息后,如何在不刷新页面的情况下显示用户的个人资料图片和消息?

qf9go6mv

qf9go6mv1#

您可以使用ajax仅刷新网页的一部分,使用不同的html文档,其中包含django html以显示配置文件图片。

相关问题