Django-channels: AttributeError: 'str' 对象没有属性'profile'



所以我在消费者中拥有我的 websocket,我在消费者中做了,当收到 websocket 时,它将在我的模型中使用 +1 a FloatField 进行更新,问题是我不知道为什么不起作用,这是我的代码:

models.py:

from django.contrib.auth.models import User
from django.db import models
from django.conf import settings
from django.utils.translation import gettext_lazy as _
class ProfileImage(models.Model):
"""
Profile model
"""
user = models.OneToOneField(
verbose_name=_('User'),
to=settings.AUTH_USER_MODEL,
related_name='profile',
on_delete=models.CASCADE
)
avatar = models.ImageField(upload_to='profile_image')
notifications = models.FloatField(default='0')

consumers.py:

async def websocket_receive(self, event):
# when a message is received from the websocket
print("receive", event)
# update the message notification badge val
other_user = self.scope['url_route']['kwargs']['username']

notification = other_user.profile.objects.get(pk=1)
notification.notifications = +1
notification.save()

问题是当收到 websocket 时,它不会更新浮点字段值,并且给我这个错误:

notification = other_user.profile.objects.get(pk=1)
AttributeError: 'str' object has no attribute 'profile'

有人知道问题是什么吗?

您要将字符串传递到变量other_user中。 然后尝试通过字符串对象访问您的用户模型。首先,你需要使用对你在 djangomodels.py中设置的类模型的非静态引用。然后,使用您保存到变量中的用户名搜索数据库。

最新更新