我不知道如何通过OnetoOne
方法获取User
与clean
模型相关联的其他字段。我有模特简介:
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'中获取值?
答案 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_name
,assembleDebug
e.t.c此处