阅读背景:

如何使用单个表单填充两个模型

来源:互联网 
  class CustomAccount(models.Model):
        user = models.OneToOneField("auth.User")
        role =  models.CharField(max_length = 50,   default = 'student',    choices=APPROVAL_CHOICES)
        balance = models.FloatField( default = 0 )
        timezone = models.CharField(max_length = 200)
        def __str__(self):

            return self.user.username +" ["+ self.role + "]"

    class CustomAccountForm(forms.ModelForm):
        username = forms.CharField(max_length=30 )
        email = forms.EmailField(max_length=255 )
        password1 = forms.CharField(label= "Password",widget=forms.PasswordInput())
        password2 = forms.CharField(label="Password confirmation", widget=forms.PasswordInput , help_text="Enter the same password as above, for verification.")    

        def save(self, commit= True):
            user = User.objects.create_user(username = self.cleaned_data['username'], email = self.cleaned_data['email'] , password = self.cleaned_data['password1'])
            user.save()
            self.user = user
            return super(CustomAccountForm, self).save(commit=commit)

        def clean_username(self):
            username = self.cleaned_data["username"]
            try:
                User.objects.get(username=username)
            except User.DoesNotExist:
                return username
            raise forms.ValidationError("A user with that username already exists.")

        def clean_password2(self):
            password1 = self.cleaned_data.get("password1", "")
            password2 = self.cleaned_data["password2"]
            if password1 != password2:
                raise forms.ValidationError("The two password fields didn't match.")
            return password2
        def clean_email(self):
            email = self.cleaned_data["email"]
            try:
                User.objects.get(email=email)
            except User.DoesNotExist:
                return email
            raise forms.ValidationError("A user with that emailaddress already exists.")    
        class Meta:
            model = CustomAccount       
            exclude = ['balance','user']
  class CustomAccount(models.Model):
        us



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: