django ValueError:无法分配“”:“Message.name“必须是“CustomUser”示例

r1zhe5dt  于 2023-05-08  发布在  Go
关注(0)|答案(3)|浏览(131)

我正在为我的网站建立一个实时聊天,在尝试将消息保存到数据库时遇到此错误消息。我使用this教程来创建实时聊天,现在正试图将其实现到我的网站上。不同的是,我不需要不同的房间,我只想授权用户访问聊天。问题来了,因为我在我的消息模型上使用外键来创建一个与CustomUser模型的链接。我正在使用渠道。
数据来源的模板:

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

        chatSocket.onmessage = function(e) {
            console.log(e);

            const data = JSON.parse(e.data)

            if(data.message) {
                document.querySelector('#chat-messages').innerHTML += ('<b>' + data.username + ': </b>' + data.message + '<br>')
            } else {
                alert('Empty!')
            }

        }

        chatSocket.onclose = function(e) {
            console.log('The socket closed unexpectedly');
        }

        document.querySelector('#chat-message-submit').onclick = function(e) {
            const messageInputDom = document.querySelector('#chat-message-input')
            const message = messageInputDom.value

            chatSocket.send(JSON.stringify({
                'message': message,
                'name': {{request.user}},
            }))

            messageInputDom.value = ''
        }

用于保存到www.example.com中的数据库的代码consumers.py

def save_message(self, name, message):
        Message.objects.create(name=name, content=message)

models.py

from django.db import models

from django.contrib.auth.models import AbstractUser

from .managers import CustomUserManager

# Create your models here.

class CustomUser(AbstractUser):
    username = models.CharField(max_length=32, blank=True, null=True)

    name = models.CharField(max_length=200, unique=True)

    steam_id = models.CharField(max_length=17, unique=True, blank=True, null=True, db_column='steam_id')
    player = models.TextField(null=True)
    user_coins = models.FloatField(default=0.00)

    is_active = models.BooleanField(default=True, db_column='status')
    is_staff = models.BooleanField(default=False, db_column='isstaff')
    is_superuser = models.BooleanField(default=False, db_column='issuperuser')

    USERNAME_FIELD = "name"
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return self.is_superuser

    def has_module_perms(self, app_label):
        return self.is_superuser

class Message(models.Model):
    name = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
    content = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('date_added',)
kiayqfof

kiayqfof1#

你不能只是传递一个字符串并引用它到CustomUser类的对象。你必须传递一个示例。首先使用id或合适的惟一属性获取相关示例(希望name是惟一的)

def get_object(self, name):
    return CustomUser.objects.get(name=name)

然后将其传递到save_message(self, name, message)方法中,

def save_message(self, name, message):
    user_obj = self.get_object(name)
    Message.objects.create(name=user_obj, content=message)
am46iovg

am46iovg2#

通过查看您的Message模型,nameForeignKeyCustomUser模型。所以问题出在你的save_message上,因为你提供了name作为string,但它必须是CustomUser示例。因此,将consumers.py中的save_message从下面的

def save_message(self, name, message):
    Message.objects.create(name=name, content=message)

def save_message(self, name, message):
    Message.objects.create(name=user_obj, content=message) <--- add custom user object accordingly
4jb9z9bj

4jb9z9bj3#

首先从customuser获取名称,然后将值放入消息中

msgname = CustomUser.objects.get(name)
message = Message.objects.create(name = msgname, content = message)

相关问题