__init __()得到了一个意想不到的关键字参数'user' [英] __init__() got an unexpected keyword argument 'user'
问题描述
我在创建用户时使用Django来创建用户和对象。但是有一个错误
i am using Django to create a user and an object when the user is created. But there is an error
__ init __()得到一个意想不到的关键字参数'user'
。
该功能是:
when calling the register()
function in view.py.
The function is:
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(用户名,电子邮件,密码)
和
LivingRoom.objects.create(user = instance)
The Django error page notifies the error information:
user=User.objects.create_user(username, email, password)
and
LivingRoom.objects.create(user=instance)
我试图搜索这个问题,找到一些案例,但仍然无法弄清楚如何解决它。
I tried to search this problem, finding some cases, but still cannot figure out how to solve it.
推荐答案
你不能做
LivingRoom.objects.create(user=instance)
因为你有一个不采取用户
作为参数。
because you have an init method that does NOT take user
as argument.
你想要一些类似
#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
这篇关于__init __()得到了一个意想不到的关键字参数'user'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!