我正在尝试为我的“人物”模型添加其他属性,即“年龄”,“城市”和“州”。我几天来一直在努力解决这个问题,并查看了如何在Django中“扩展用户类”的文档。但是,我被卡住了,当我尝试创建一个新帐户时,我收到以下错误:
TypeError at /polls/signup/add
'age' is an invalid keyword argument for this function
人物模型:
class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=200, null=True)
last_name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
city = models.CharField(max_length=200, null=True)
state = models.CharField(max_length=200, null=True)
age = models.CharField(max_length=50, null=True)
创建帐户视图(我很确定这是问题发生的地方):
def create_account(request):
if request.method == 'POST':
new_user = User(username = request.POST["username"],
email=request.POST["email"],
first_name=request.POST["first_name"],
last_name=request.POST["last_name"],
age=request.POST["age"],
city=request.POST["city"],
state=request.POST["state"])
new_user.set_password(request.POST["password"])
new_user.save()
Person.objects.create(user=new_user,
first_name=str(request.POST.get("first_name")),
last_name=str(request.POST.get("last_name")),
email=str(request.POST.get("email")),
age=str(request.POST.get("age")),
city=str(request.POST.get("city")),
state=str(request.POST.get("state")))
new_user.is_active = True
new_user.save()
return redirect('../')
else:
return render(request, 'polls/create_account.html')
关于如何解决此问题并允许用户添加通用用户模型中未包含的这些奖励字段的任何想法?
答案 0 :(得分:2)
您应该使用Person模型而不是User。
if request.method == 'POST':
new_user = User(username = request.POST["username"],
email=request.POST["email"],
first_name=request.POST["first_name"],
last_name=request.POST["last_name"],
)
new_user.set_password(request.POST["password"])
new_user.save()
Person.objects.create(user=new_user,
age=str(request.POST.get("age")),
city=str(request.POST.get("city")),
state=str(request.POST.get("state")))
new_user.is_active = True
new_user.save()
return redirect('../')
else:
return render(request, 'polls/create_account.html')