0

我正在做一个配置文件,在 django 中查看我的模型:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    tipo = models.CharField(max_length=1,choices=TIPO_U)
    sexo = models.CharField(max_length=1,choices=SEXO)
    datanasc = models.DateField(blank=True, null=True)
    turma = models.ForeignKey(Turma, blank=True, null=True)
    ano = models.CharField(max_length=10, blank=True, null=True)
    cpf = models.CharField(max_length=20, blank=True, null=True)
    matricula = models.CharField(max_length=10, blank=True, null=True)
    endereco = models.CharField(max_length=400, blank=True, null=True)
    telefone = models.CharField(max_length=20, blank=True, null=True)

查看我的表格:

class ProfileForm(ModelForm):
    username = forms.CharField(label="Usuário:", required=True)
    password1 = forms.CharField(required=True, label="Senha:",
        widget=forms.PasswordInput(render_value=True))
    password2 = forms.CharField(required=True, label="Confirmar Senha:",
        widget=forms.PasswordInput(render_value=True))
    email = forms.EmailField(label="E-mail:", required=True)
    first_name = forms.CharField(label="Nome completo:", required=True)

    def clean_username(self):
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(("Já existe um usuário com esse nome por favor escolha outro."))

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1", "")
        password2 = self.cleaned_data["password2"]
        if password1 != password2:
            raise forms.ValidationError(("A confirmação da senha não confere, verifique."))
        return password2

    class Meta:
      model = UserProfile
      exclude = ('user',)

    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        try:
            self.fields['username'].initial = self.instance.user.username
            self.fields['email'].initial = self.instance.user.email
            self.fields['first_name'].initial = self.instance.user.first_name
        except User.DoesNotExist:
            pass

    def save(self, *args, **kwargs):
        if (self.instance.pk is None):
            u = User.objects.create_user(
                username=self.cleaned_data['username'],
                email=self.cleaned_data['email'])
            u.set_password(self.cleaned_data["password1"])
            u.is_active = True
        else:
            u = self.instance.user
            u.username = self.cleaned_data['username']
            u.email = self.cleaned_data['email']

        u.first_name = self.cleaned_data['first_name']  
        u.save()
        self.user = u
        profile = super(ProfileForm, self).save(*args,**kwargs)
        return profile

运行插入时出现以下错误:

profile_userprofile.user_id 不能为 NULL

我不知道它是否正确,但我做到了:self.user = u

编辑

我的错误是忘记放:实例

self.instance.user = u

4

1 回答 1

0

尝试用/替换最后三行save方法

profile = super(ProfileForm, self).save(commit=False)
profile.user = u
profile.save()
return profile

或者您可以在form.save参考模型表单文档之外执行此操作

于 2012-04-18T08:01:21.503 回答