【问题标题】:How to get values from a linked model for validation?如何从链接模型中获取值进行验证?
【发布时间】:2018-04-23 10:19:48
【问题描述】:

我不知道如何在clean 方法中获取由OnetoOneUser 模型链接的其他字段。我有模特简介:

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

我想在方法 clean 中进行验证:

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

我只获取默认的用户模型字段(用户名、名字..)如何从字段“书籍”中获取值?

【问题讨论】:

  • ProfileForm 是模型形式吗?如果是,您是否在 ProfileForm 的元数据中提到了 model 参数
  • 您应该在Meta 类中添加model = Profile
  • 我们希望在这里实现什么?我能想到两个潜在的用例;您正在寻找创建用户或更新现有用户的帖子。

标签: python django django-models django-forms


【解决方案1】:

您正在继承 Django 的 UserCreationForm 以创建用户,并在 User 模型上运行。在此表单中,您将无法访问 UserProfile 模型实例。

从 Django 源代码中可以看出,UserCreationForm 仅限于 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 方法因此在此处正确返回 usernamefirst_name

【讨论】:

    猜你喜欢
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多