Home > Software design >  ValueError: Cannot assign "": "Message.name" must be a "CustomUser" in
ValueError: Cannot assign "": "Message.name" must be a "CustomUser" in

Time:02-07

I am building a live chat for my website and encountered this error message while trying to save messages to database. I used this tutorial to create the live chat and am now trying to implement it to my site. The difference is that I do not need different rooms and I want only authorized users to access the chat. The problem comes because I use foreign key on my Messages model to create a link with CustomUser model. I am using channels.

template where the data comes from:

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 = ''
        }

code used for saving into database in 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',)

CodePudding user response:

You can't just pass a string and reference it to an object of CustomUser class. You'll have to pass an instance of it. First get the relevant instance by using id or a suitable unique attribute,(hope the name is unique)

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

And then pass it in your save_message(self, name, message) method,

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

CodePudding user response:

By looking at your Message model, name is a ForeignKey to CustomUser model. So problem is in your save_message as you provide name as string but it must be CustomUser instance. So change save_message in your consumers.py from this

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

To

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