Django:扩展用户模型无法保存

时间:2017-05-21 05:58:50

标签: django django-forms

我已将django用户模型扩展为另一个名为profile的模型:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    chosenCharity = models.ForeignKey('meta.Charity', db_column='chosenCharityid', related_name='user_chosenCharity')
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

当我尝试使用下面的代码在视图中创建新用户时,我收到以下错误"(1048," Column' selectedCharityid'不能为null") ":

@transaction.atomic
def register(request):
    selectedTeams = StraightredTeam.objects.filter(Q(teamid=request.session['team1id']) | Q(teamid=request.session['team2id'])).order_by('teamname')
    request.POST.get('currentCharities')

    next_url = request.POST.get('next', request.GET.get('next', reverse('straightred.payment')))
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            new_user = form.save()

我知道当用户已经创建时我应该可以使用:

user = User.objects.get(pk=user_id)
user.profile.chosenCharity = 12
user.save()

但我不确定在创建用户时如何执行此操作。任何帮助将不胜感激。

以下是帮助注册表的副本:

class RegistrationForm(BootstrapModelForm, UserCreationForm):
    email_opt_in = forms.BooleanField(label='Receive DWAD e-mail updates', required=False)

    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        # The default Django user model doesn't require these fields to be set
        # but we do.

        self.fields['email'].required = True

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email__iexact=email).exists():
            raise ValidationError('There is already an account registered with this e-mail address.')
        return email

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', 'username']

慈善模式:

class Charity(models.Model):
    name = models.CharField(max_length=50, unique=True)
    website = models.URLField()
    enabled = models.BooleanField(default=True)

    def __unicode__(self):
        return self.name

    class Meta:
        ordering = ['name']
        verbose_name_plural = 'charities'

1 个答案:

答案 0 :(得分:1)

不要在post_save信号中创建Profile对象。您无法在create_user_profile方法中访问所需的慈善机构ID。所以删除那部分代码。

而是在您的register视图中保存用户对象后立即保存配置文件对象:

@transaction.atomic
def register(request):
    selectedTeams = StraightredTeam.objects.filter(Q(teamid=request.session['team1id']) | Q(teamid=request.session['team2id'])).order_by('teamname')
    request.POST.get('currentCharities')

    next_url = request.POST.get('next', request.GET.get('next', reverse('straightred.payment')))
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            charity_id = request.session['chosenCharityid']
            # create profile object
            Profile.objects.create(user=new_user, chosenCharity_id=charity_id)

编辑:

我看到你正在使用另一种方法save_user_profile来接收post_save信号。

也不要使用它。这是一个简单直接的事情。

使用您自己的代码示例:

user = User.objects.get(pk=user_id)
# here you are assigning a new charity id to the profile object
user.profile.chosenCharity = 12
# you save the user object on which nothing has changed
# instead you should save the profile object
user.save() # no need
user.profile.save() # direct and logical