gpt4 book ai didi

python - 保存通知对象django websockets的逻辑

转载 作者:行者123 更新时间:2023-12-01 07:56:26 26 4
gpt4 key购买 nike

当在 2 人 Django Channels Websockets 聊天应用程序中收到来自另一个 other_user 的消息时,我很难理解如何保存通知。

现在我有一个在 def create_chat_message 之后调用的函数 def create_notification

def create_chat_message 每次在 Thread 中发送新消息时都会创建一个新的 ChatMessage 对象。它需要 args thread=thread_obj, user=me, message=msg 因此显然每条单独的消息都与用户一起保存而不是发送。

def create_notification 获取 ChatMessageid 的最后一个对象,并创建一个新的 Notification 对象。

created_notification = Notification.objects.create(notification_user=user, notification_chat=last_chat)

本质上,发送消息的人与 Notification 模型中的 notification_user 字段相关联,并与 ChatMessage id 一起保存。

但是,如果我向 Tom 发送消息,我发送的消息应该只与 Tom 的通知相关联,而不是与我自己的通知相关联。

当我渲染通知对象时,我会得到所有这些对象的列表,包括我显然已发送的消息的通知。

如何呈现我与不同用户所在的每个线程的所有通知?

我保存这些错误吗?我是否应该配置保存通知功能,以便它仅保存来自其他用户的传入消息?或者添加某种 if 语句

我不需要以某种方式与通知关联,以便在呈现通知时,我作为收件人的所有通知都会显示吗?

我的 Notification 模型将 ChatMessage 作为 ForeignKey,它有一个 thread 字段,它是一个 ForeignKeyThread,其中包含 firstsecond(代表我和单个线程中的另一个用户)。

我已经研究这个好几天了,有一种感觉我错过了一些简单的东西,并且让这个变得比它需要的更加复杂。

模型.py

class ThreadManager(models.Manager):
def by_user(self, user):
qlookup = Q(first=user) | Q(second=user)
qlookup2 = Q(first=user) & Q(second=user)
qs = self.get_queryset().filter(qlookup).exclude(qlookup2).distinct()
return qs

# method to grab the thread for the 2 users
def get_or_new(self, user, other_username): # get_or_create
username = user.username
if username == other_username:
return None, None
# looks based off of either username
qlookup1 = Q(first__username=username) & Q(second__username=other_username)
qlookup2 = Q(first__username=other_username) & Q(second__username=username)
qs = self.get_queryset().filter(qlookup1 | qlookup2).distinct()
if qs.count() == 1:
return qs.first(), False
elif qs.count() > 1:
return qs.order_by('timestamp').first(), False
else:
Klass = user.__class__
try:
user2 = Klass.objects.get(username=other_username)
except Klass.DoesNotExist:
user2 = None
if user != user2:
obj = self.model(
first=user,
second=user2
)
obj.save()
return obj, True
return None, False

class Thread(models.Model):
first = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_first')
second = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_second')
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)

objects = ThreadManager()

def __str__(self):
return f'{self.id}'

@property
def room_group_name(self):
return f'chat_{self.id}'

def broadcast(self, msg=None):
if msg is not None:
broadcast_msg_to_chat(msg, group_name=self.room_group_name, user='admin')
return True
return False

class ChatMessage(models.Model):
thread = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.SET_NULL)
user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='sender', on_delete=models.CASCADE)
message = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)

def __str__(self):
return f'{self.id}'

class Notification(models.Model):
notification_user = models.ForeignKey(User, on_delete=models.CASCADE)
notification_chat = models.ForeignKey(ChatMessage, on_delete=models.CASCADE)
notification_read = models.BooleanField(default=False)

def __str__(self):
return f'{self.id} attached to {self.notification_user}'

消费者.py

class ChatConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print('connected', event)

other_user = self.scope['url_route']['kwargs']['username']
me = self.scope['user']
#print(other_user, me)
thread_obj = await self.get_thread(me, other_user)
self.thread_obj = thread_obj
chat_room = f"thread_{thread_obj.id}"
self.chat_room = chat_room
# below creates the chatroom
await self.channel_layer.group_add(
chat_room,
self.channel_name
)

await self.send({
"type": "websocket.accept"
})

async def websocket_receive(self, event):
# when a message is recieved from the websocket
print("receive", event)

message_type = json.loads(event.get('text','{}')).get('type')
print(message_type)
if message_type == "notification_read":
user = self.scope['user']
username = user.username if user.is_authenticated else 'default'
# Update the notification read status flag in Notification model.
notification = Notification.objects.filter(notification_user=user)
notification.notification_read = True
notification.save() #commit to DB
print("notification read")
return

front_text = event.get('text', None)
if front_text is not None:
loaded_dict_data = json.loads(front_text)
msg = loaded_dict_data.get('message')
user = self.scope['user']
username = user.username if user.is_authenticated else 'default'
notification_id = 'default'
myResponse = {
'message': msg,
'username': username,
'notification': notification_id,
}
print(myResponse)
await self.create_chat_message(user, msg)
await self.create_notification(user, msg)

# broadcasts the message event to be sent, the group send layer
# triggers the chat_message function for all of the group (chat_room)
await self.channel_layer.group_send(
self.chat_room,
{
'type': 'chat_message',
'text': json.dumps(myResponse)
}
)

# chat_method is a custom method name that we made
async def chat_message(self, event):
# sends the actual message
await self.send({
'type': 'websocket.send',
'text': event['text']
})

async def websocket_disconnect(self, event):
# when the socket disconnects
print('disconnected', event)

@database_sync_to_async
def get_thread(self, user, other_username):
return Thread.objects.get_or_new(user, other_username)[0]

@database_sync_to_async
def create_chat_message(self, me, msg):
thread_obj = self.thread_obj
return ChatMessage.objects.create(thread=thread_obj, user=me, message=msg)

@database_sync_to_async
def create_notification(self, user, msg):
last_chat = ChatMessage.objects.latest('id')
created_notification = Notification.objects.create(notification_user=user, notification_chat=last_chat)
print(created_notification)
return created_notification

导航栏.html

  <div id="notificationsBody" class="notifications">
{% for notifications in notification|slice:"0:10" %}
<a href="{% url 'chat:thread' user %}">
<span id="notification-{{notification.id}}">
{{ notifications.notification_chat.message }}
via {{ notifications.notification_chat.user }}
at {{ notifications.notification_chat.timestamp }}
</span>
</a>
{% endfor %}

最佳答案

您正在创建的Notification对象,需要将Notification.notification_user设置为other_user。该通知针对的是其他用户,而不是发送该消息的用户。

other_username = self.scope['url_route']['kwargs']['username']
other_user = User.objects.get(username=other_username)
await self.create_notification(other_user, msg) #other_user, not the current user

但是,在更新已读取的通知时,需要当前用户。

关于python - 保存通知对象django websockets的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55954242/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com