我正在遵循Django文档这里的指导,以实现一个简单的目标:一旦创建了新用户就创建用户资料。
我有一个'accounts'应用程序,我的accounts.models看起来像这样:
# -*- coding: utf-8 -*-
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from main.models import Store
class UserProfile(models.Model):
GENRE_CHOICES = (
('m', 'Masculino'),
('f', 'Feminino'),
)
MARITAL_STATUS_CHOICES = (
('s', 'Solteiro'),
('c', 'Casado'),
('d', 'Divorciado'),
('v', 'Viúvo'),
)
user = models.ForeignKey(User, unique=True)
birth_date = models.DateField()
genre = models.CharField(max_length=1, choices=GENRE_CHOICES)
address = models.CharField(max_length=150)
postal_code_4 = models.PositiveIntegerField()
postal_code_3 = models.PositiveIntegerField()
locatity = models.CharField(max_length=30)
marital_status = models.CharField(max_length=1, choices=MARITAL_STATUS_CHOICES)
child_amount = models.PositiveSmallIntegerField()
is_merchant = models.BooleanField(default=False)
store = models.ForeignKey(Store, 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)
我觉得一切看起来都很好,但是当我尝试添加新用户(使用django管理界面)时,我没有得到新创建的用户和用户配置文件,而是收到以下错误信息: InternalError at /admin/auth/user/add/ current transaction is aborted, commands ignored until end of transaction block
这里是跟踪错误的部分:
/djangoProjects/lwboanova/lwboanova/apps/accounts/models.py in create_user_profile
34: UserProfile.objects.create(user=instance)
看起来像是完整性错误,但我不知道原因。
如果你们中的任何人能够帮助我,那就太好了。
UserProfile.objects.create(user=instance)
之后仍然使用instance.profile.save()
。看起来每个人都在遵循同样古老的博客!据我所知,create
隐式调用save
。 - haccks