__init__() got an unexpected keyword argument 'user'

前端 未结 4 539
暗喜
暗喜 2020-12-25 12:14

i am using Django to create a user and an object when the user is created. But there is an error

__init__() got an unexpected keyword argument \'user\'<

4条回答
  •  春和景丽
    2020-12-25 13:04

    You can't do

    LivingRoom.objects.create(user=instance)
    

    because you have an __init__ method that does NOT take user as argument.

    You need something like

    #signal function: if a user is created, add control livingroom to the user    
    def create_control_livingroom(sender, instance, created, **kwargs):
        if created:
            my_room = LivingRoom()
            my_room.user = instance
    

    Update

    But, as bruno has already said it, Django's models.Model subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields.

    So, following better principles, you should probably have something like

    class LivingRoom(models.Model):
        '''Living Room object'''
        user = models.OneToOneField(User)
    
        def __init__(self, *args, temp=65, **kwargs):
            self.temp = temp
            return super().__init__(*args, **kwargs)
    

    Note - If you weren't using temp as a keyword argument, e.g. LivingRoom(65), then you'll have to start doing that. LivingRoom(user=instance, temp=66) or if you want the default (65), simply LivingRoom(user=instance) would do.

提交回复
热议问题