【问题标题】:Django: Form object has no attribute cleaned_data - save() methodDjango:表单对象没有属性cleaned_data - save() 方法
【发布时间】:2013-07-10 10:49:26
【问题描述】:

好吧,我实际上是偶然解决了这个问题,只是想了解发生了什么。

我有自己的用户注册表单 BaseCreationForm,它扩展了 ModelForm 并使用 UserProfile 作为其模型。所有的验证方法都运行良好,但保存方法让我很伤心。每当我尝试创建用户时(配置文件是在视图中创建的,我可能会重构它),Django 会告诉我“BaseCreationForm 对象没有属性清理数据”。

但是,当出于沮丧和想法耗尽时,我在 save() 方法中创建用户之前添加了一个简单的“打印自我”语句,问题消失了,用户正在正常创建。下面是几个可用的 clean() 方法,save() 方法和视图中调用 clean() 和 save() 方法的 sn-p。

clean() 方法正常工作

#example clean methods, both work beautifully
def clean_email(self):
    email = self.cleaned_data["email"]
    if not email:
        raise forms.ValidationError(self.error_messages['no_email'])

    try:
        User.objects.get(email=email)
    except User.DoesNotExist:
        return email
    raise forms.ValidationError(self.error_messages['duplicate_email'])

def clean_password2(self):
    # Check that the two password entries match
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError(
            self.error_messages['password_mismatch'])
    return password2

save() 方法:

 #save method requiring wizardry
 def save(self, commit=True):
    #This line makes it work. When commented, the error appears
    print self
    ###  
    user = User.objects.create_user(
        username=self.cleaned_data.get("username"),
        first_name=self.cleaned_data["first_name"],
        last_name=self.cleaned_data["last_name"],
        email=self.cleaned_data["email"],
        )
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()
    return user

还有视图(省略了一些东西):

class RegistrationView(FormView):
    template_name = 'register.html'
    form_class = BaseCreationForm
    model = UserProfile
    success_url = '/account/login/'

    def form_valid(self, form):
        form                    = BaseCreationForm(self.request.POST,
                                                  self.request.FILES)
        user                    = form.save()
        profile                 = user.get_profile()
        profile.user_type       = form.cleaned_data['user_type']
        profile.title           = form.cleaned_data['title']
        profile.company_name    = form.cleaned_data['company_name']
        .
        .
        .
        profile.save()
        return super(RegistrationView, self).form_valid(form)

【问题讨论】:

    标签: python django django-forms


    【解决方案1】:

    您不应该在 form_valid 方法中重新实例化表单。当表单已经有效时调用它,并且确实将表单传递到方法中。你应该改用它。

    (请注意,实际错误是因为您根本没有调用form.is_valid(),但正如我在上面所说的那样,您不应该这样做,因为视图已经在这样做了。)

    【讨论】:

    • 哦,我明白了,谢谢。它存在的原因是我正在上传一个文件并且之前遇到了麻烦,一些消息来源说我应该确保它包含(self.request.FILES)。但是错误一定是在其他地方,因为现在我刚刚注释掉它仍然有效。
    猜你喜欢
    • 2011-12-26
    • 2016-06-24
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多