Home > Back-end >  Why is the error showing 5 positional arguments while registering the model
Why is the error showing 5 positional arguments while registering the model

Time:04-11

I am trying to make a chat application on Django. I have created a model to input into a database of the format room_no, user, message. Additionally, I have included the init function to extract the data from the database in the form of a string so I can display it on the HTML page. Apart from my method, is there another way to do this? If not, could you please explain my error?

Models:

 class chatbox(models.Model):
        name = models.CharField(max_length=100, blank=False,default='Anonymous')
        room = models.CharField(max_length=100,blank=True)
        message = models.CharField(max_length=500000,blank=True)
        def __init__(self,name,message):
            self.name = name 
            self.message = message 

ADMIN

admin.site.register(models.chatbox)

Error:

TypeError at /admin/DjangoChat/chatbox/
chatbox.__init__() takes 3 positional arguments but 5 were given

CodePudding user response:

You may be tempted to customize the model by overriding the init method. If you do so, however, take care not to change the calling signature as any change may prevent the model instance from being saved. Rather than overriding init, try using one of these approaches:

1-Add a classmethod on the model class:

 class Chatbox(models.Model):
    name = models.CharField(max_length=100, blank=False,default='Anonymous')
    room = models.CharField(max_length=100,blank=True)
    message = models.CharField(max_length=500000,blank=True)
    @classmethod
    def create(cls, name, message):
        chatbox= cls(name=name, message=message)
        # do something with the book
        return chatbox

 chatbox= Chatbox.create("usama", "hello world")

2-Add a method on a custom manager (usually preferred):

class Chatbox(models.Manager):
    def create_chatbox(self, name, message):
        chatbox= self.create(name=name, message=message)
        # do something with the book
        return chatbox

class ChatboxManager(models.Model):
    name = models.CharField(max_length=100, blank=False,default='Anonymous')
    room = models.CharField(max_length=100,blank=True)
    message = models.CharField(max_length=500000,blank=True)

    objects = ChatboxManager()

chatbox= Chatbox.objects.create_chatbox("usama", "hello world")

you can get more detailed from Documentation

  • Related