如何从链接模型中获取值以进行验证?

时间:2018-04-23 10:19:49

标签: python django django-models django-forms

我不知道如何通过OnetoOne方法获取Userclean模型相关联的其他字段。我有模特简介:

class Profile(models.Model):
   user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
   books = models.CharField(max_length=25)

我希望在方法清理方面进行验证:

class ProfileForm(UserCreationForm):
   class Meta:
      fields = '__all__'
   def clean(self):
      cleaned_data = super().clean()
      get_books = cleaned_data.get('books')
      #this I get error 

我只获取默认的用户模型字段(username,first_name ..)如何从字段'books'中获取值?

1 个答案:

答案 0 :(得分:0)

您正在对Django User进行子类化,这是为了创建用户,并在UserProfile模型上运行。在此表单中,您将无法访问UserCreationForm模型实例。

从Django源代码中可以看出,User仅限于User模型,并且仅显示class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField(label=_("Password"), strip=False, widget=forms.PasswordInput) password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification.")) class Meta: model = User fields = ("username",) 模型中存在的字段

clean

username方法正确地返回first_nameassembleDebug e.t.c此处