【问题标题】:Django-channels: AttributeError: 'str' object has no attribute 'profile'Django-channels:AttributeError:'str'对象没有属性'profile'
【发布时间】:2020-08-09 20:41:01
【问题描述】:

所以我在消费者中有我的 websocket,我在消费者中做了,当接收到 websocket 时,它会在我的模型中更新为 +1 一个 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 时,它不会更新 floatfield 值,它给了我这个错误:

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

有人知道问题出在哪里吗?

【问题讨论】:

    标签: python django websocket django-channels


    【解决方案1】:

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

    【讨论】:

    • 如何进行非静态引用?
    • 指的是用于创建模型的类。在这种情况下,“个人资料图像”。要将任何“ProfileImage”对象保存到数据库,它应该类似于“ProfileImage.objects.get(pk=primaryKeyOfTheDesiredProfile)”。我会考虑制作一个 Profile 模型,并使 Profileimage 成为模型中的一个字段。使用非静态引用和主键访问此模型后,您可以将其保存为名为“profile”的变量。然后您可以调用您在其中创建的任何字段,例如“profile.profileimage”
    猜你喜欢
    • 2012-11-05
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2020-04-01
    • 2021-11-12
    相关资源
    最近更新 更多