我正在尝试在网站上注册新用户,
class UserInfo(models.Model):
user = models.ForeignKey(User,primary_key=True)#user profile
email_id=models.CharField(max_length=32, null=True, blank=True)
当我注册用户时,我遇到了完整性错误,请帮我解决问题。
def registration(request):
registration_dict = {}
if 1==1 :
#if request.POST:
#username=request.POST['email']
#password=request.POST['password']
username="admin@admin.com"
password='123456'
#try:
UserInfo.objects.get_or_create(email_id=username,user__username=username,user__email=username,user__password=password)
#except:
# registration_dict["status"]="0"
# registration_dict["message"]="Username already present"
# return HttpResponse(simplejson.dumps(registration_dict),content_type="application/json")
registration_dict["status"]="1"
registration_dict["message"]="Thank You for registering"
return HttpResponse(simplejson.dumps(registration_dict),content_type="application/json")
else:
registration_dict["status"]="0"
registration_dict["message"]="Unable to process the request"
return HttpResponse(simplejson.dumps(registration_dict),content_type="application/json")
编辑1
我试过改变
UserInfo.objects.get_or_create(email_id=username,user__username=username,user__email=username,user__password=password,user_id=1)
然后错误更改为
'Cannot add or update a child row: a foreign key constraint fails (`app_info`.`appdata_userinfo`, CONSTRAINT `user_id_refs_id_b0fd803b` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`))')
答案 0 :(得分:1)
如果原始User对象不存在,您将遇到各种问题。因此,您需要将该过程分解为两个步骤。
User
对象,如果它没有创建它。由于存在UserInfo
,您无法一步完成:
ForeignKey
答案 1 :(得分:1)
从有限的信息我会说问题是 它找不到匹配的UserInfo。然后它尝试创建一个新的UserInfo,但没有User分配给User ForeignKey。我建议如下:
user = authenticate(username=email, password=password)
if user is None:
user = User(username=email, password=password, email=email)
user_info = UserInfo.objects.get_or_create(user=user, email_id=email)
答案 2 :(得分:1)
我无法理解你为什么需要UserInfo,因为用户已经有电子邮件。 可以通过拆分提取过程来纠正问题
username = "admin@admin.com"
password = '123456'
user,status = User.objects.get_or_create(username=username, password=password)
user_info = UserInfo.objects.get_or_create(user=user,email_id=username)