Python __init__() 得到了一个意外的关键字参数“用户”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19986089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:09:42  来源:igfitidea点击:

__init__() got an unexpected keyword argument 'user'

pythondjangodjango-modelsdjango-formsdjango-views

提问by noben

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

我正在使用 Django 在创建用户时创建一个用户和一个对象。但是有一个错误

__init__() got an unexpected keyword argument 'user'

__init__() got an unexpected keyword argument 'user'

when calling the register()function in view.py. The function is:

register()在 view.py 中调用函数时。功能是:

def register(request):  
    '''signup view'''     
    if request.method=="POST":  
        form=RegisterForm(request.POST)  
        if form.is_valid():  
            username=form.cleaned_data["username"]  
            email=form.cleaned_data["email"]  
            password=form.cleaned_data["password"]  
            user=User.objects.create_user(username, email, password)  
            user.save()
            return HttpResponseRedirect('/keenhome/accounts/login/')
        else: 
            form = RegisterForm()      
            return render_to_response("polls/register.html", {'form':form}, context_instance=RequestContext(request))  

    #This is used for reinputting if failed to register    
    else: 
        form = RegisterForm()      
        return render_to_response("polls/register.html", {'form':form}, context_instance=RequestContext(request))

and the object class is:

对象类是:

class LivingRoom(models.Model):
    '''Living Room object'''
    user = models.OneToOneField(User)

    def __init__(self, temp=65):
        self.temp=temp

    TURN_ON_OFF = (
        ('ON', 'On'),
        ('OFF', 'Off'),
    )

    TEMP = (
        ('HIGH', 'High'),
        ('MEDIUM', 'Medium'),
        ('LOW', 'Low'),
    )

    on_off = models.CharField(max_length=2, choices=TURN_ON_OFF)
    temp = models.CharField(max_length=2, choices=TEMP)

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

post_save.connect(create_control_livingroom, sender=User)

The Django error page notifies the error information: user=User.objects.create_user(username, email, password)and LivingRoom.objects.create(user=instance)

Django 错误页面通知错误信息: user=User.objects.create_user(username, email, password)LivingRoom.objects.create(user=instance)

I tried to search this problem, finding some cases, but still cannot figure out how to solve it.

我试图搜索这个问题,找到一些案例,但仍然无法弄清楚如何解决它。

采纳答案by shad0w_wa1k3r

You can't do

你不能做

LivingRoom.objects.create(user=instance)

because you have an __init__method that does NOT take useras argument.

因为你有一个__init__user作为参数的方法。

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

回答by bruno desthuilliers

LivingRoom.objects.create()calls LivingRoom.__init__()- as you might have noticed if you had read the traceback - passing it the same arguments. To make a long story short, a Django models.Modelsubclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields. The correct way to provide default values for fields is in the field constructor using the defaultkeyword as explained in the FineManual.

LivingRoom.objects.create()调用LivingRoom.__init__()- 如果您已经阅读了回溯,您可能已经注意到 - 将相同的参数传递给它。长话短说,Djangomodels.Model子类的初始值设定项最好单独保留,或者应该接受与模型的元字段匹配的 *args 和 **kwargs。为字段提供默认值的正确方法是在字段构造函数中使用defaultFineManual 中解释的关键字。

回答by Luis Berrocal

I got the same error.

我得到了同样的错误。

On my view I was overriding get_form_kwargs() like this:

在我看来,我正在像这样覆盖 get_form_kwargs():

class UserAccountView(FormView):
    form_class = UserAccountForm
    success_url = '/'
    template_name = 'user_account/user-account.html'

def get_form_kwargs(self):
    kwargs = super(UserAccountView, self).get_form_kwargs()
    kwargs.update({'user': self.request.user})
    return kwargs

But on my form I failed to override the init() method. Once I did it. Problem solved

但是在我的表单上我没有覆盖init() 方法。一旦我做到了。问题解决了

class UserAccountForm(forms.Form):
    first_name = forms.CharField(label='Your first name', max_length=30)
    last_name = forms.CharField(label='Your last name', max_length=30)
    email = forms.EmailField(max_length=75)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(UserAccountForm, self).__init__(*args, **kwargs)

回答by Phillip Kigenyi

Check your imports. There could be two classes with the same name. Either from your code or from a library you are using. Personally that was the issue.

检查您的进口。可能有两个具有相同名称的类。来自您的代码或您正在使用的库。就个人而言,这就是问题所在。