首页 文章

IntegrityError -userprofile.u_id可能不是NULL,django用户注册

提问于
浏览
1

我正在尝试使用Django UserProfile功能注册用户 . 我有一个Extended UserProfile模型 . 我的文件如下所示 . 我收到“accounts_userprofile.u_id可能不是NULL”,我在保存表单时尝试使用'commit = false',但它没有用 . 我的父模型的字段设置为null = True,blank = True . 我已经放弃了 table 并添加了几次,但没有任何效果 . 请帮忙 . 先谢谢

我的模型如下:

class UserBase(models.Model):
class Meta:
    abstract = True
    u_id = models.IntegerField(null = True,blank = True)
    email = models.CharField(max_length=200, null = True,blank = True)
    website=models.CharField(max_length=200, null = True, blank = True)
    age = models.IntegerField(blank = True, null = True)
    location = models.CharField(max_length= 200, null=True, blank = True)
    username = models.CharField(max_length = 100, null = True, blank = True)

UserProfile模型如下:

class UserProfile(UserBase):
user = models.ForeignKey(User, null= True, blank = True, unique = True)

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0]) 
def __unicode__(self):
    return "User Profile for: " + self.user.username

def create_user_profile(sender,** kw):user = kw ['instance']如果kw ['created']:up = UserProfile(user = user)

up.save()

post_save.connect(create_user_profile,sender = User,dispatch_uid =“user_create_profile”)

我的注册视图如下:

def register(request,template_name =“registration / register.html”):if request.method =='POST':postdata = request.POST.copy()
form = UserCreationForm(postdata)
如果form.is_valid():

un = postdata.get('username','')
pw = postdata.get('password1','')

来自django.contrib.auth导入登录,验证

new_user = authenticate(username = un,password = pw)
form.save()
#if new_user和new_user.is_active:
#login(request,new_user)
#url = urlresolvers.reverse('my_account')
#return HttpResponseRedirect(url)
else:form = UserCreationForm()page_title ='User Registration'return render_to_response(template_name,locals(),context_instance = RequestContext(request))>

1 回答

  • 1

    来自Django Docs:

    https://docs.djangoproject.com/en/1.4/ref/models/fields/

    Field.unique如果为True,则该字段在整个表中必须是唯一的 . 这在数据库级别和模型验证中强制执行 . 如果尝试在唯一字段中保存具有重复值的模型,则模型的save()方法将引发django.db.IntegrityError . 此选项对除ManyToManyField和FileField之外的所有字段类型都有效 .

    您告诉UserProfiles UserProfiles.u_id是唯一的,它不是(空白/ null) . 所以你得到了错误 . 您可能需要考虑将u_id更改为AutoField primary_key . 然后使用models.ForeignKey('UserBase')连接它们

相关问题