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()