__init __()得到了一个意外的关键字参数'user'

时间:2013-11-14 18:59:59

标签: python django django-models django-forms django-views

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

__init__() got an unexpected keyword argument 'user'

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

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))

,对象类是:

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)

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

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

4 个答案:

答案 0 :(得分:9)

你做不到

LivingRoom.objects.create(user=instance)

因为你有一个不以user为参数的init方法。

你想要像

这样的东西
#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

答案 1 :(得分:7)

我得到了同样的错误。

在我的观点中,我像这样覆盖了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

但在我的表单上,我未能覆盖 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)

答案 2 :(得分:2)

LivingRoom.objects.create()调用LivingRoom.__init__() - 您可能已经注意到,如果您已经阅读了回溯 - 将相同的参数传递给它。总而言之,Django models.Model子类的初始化器最好不要单独使用,或者接受* args和** kwargs匹配模型的元字段。为字段提供默认值的正确方法是使用default关键字在字段构造函数中,如FineManual中所述。

答案 3 :(得分:0)

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