如何在方法保存上设置字段

时间:2012-04-18 07:53:54

标签: django authentication profile

我正在做个人资料,请参阅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

修改

我的错误是忘了把:instance

self.instance.user = u

1 个答案:

答案 0 :(得分:0)

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

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

或者你可以在form.save,ref the modelforms doc

之外进行