Django - 使用自定义用户模型进行用户创建会导致内部错误 [英] Django - User creation with custom user model results in internal error

查看:209
本文介绍了Django - 使用自定义用户模型进行用户创建会导致内部错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我知道这是一个愚蠢的问题,但我被阻止,我无法弄清楚该怎么做。

Ok, I know this is a silly question but I am blocked and I can't figure out what to do.

我已经在google和stackoverflow上搜索,没有找到任何答案:
我尝试过:

I have searched on google and stackoverflow but did not found any answer : I tried this :

  • Adding custom fields to users in django
  • Django - Create user profile on user creation
  • https://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

我的模型如下:


My model is the following :

class UserProfile(models.Model):
    user = models.OneToOneField(User)

    quota = models.IntegerField(null = True)


def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

我的用户注册视图如下:

And my view for user registration is the following :

def register(request):
    if request.method == 'POST': # If the form has been submitted...
        form = RegistrationForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            cd = form.cleaned_data

            #Then we create the user
            user = User.objects.create_user(cd['username'],cd["email"],cd["password1"])

            user.get_profil().quota = 20

            user.save()

            return HttpResponseRedirect('')

    else:
        form = RegistrationForm() # An unbound form

    return render(request, 'registration_form.html', {'form': form,})

启动InternalError的行是:

The line that launches an InternalError is :

user = User.objects.create_user(cd['username'],cd["email"],cd["password1"])

错误是:

InternalError at /register/

current transaction is aborted, commands ignored until end of transaction block

感谢您的帮助

推荐答案

user = User.objects.create_user(username=form.cleaned_data['username'],
                                password=form.cleaned_data['password'], 
                                email=form.cleaned_data['email'])
user.is_active = True
user.save()

这篇关于Django - 使用自定义用户模型进行用户创建会导致内部错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆