2013-07-10 112 views
1

好吧,我真的解決了這個問題,只是想知道發生了什麼。Django:表單對象沒有任何屬性deleted_data - save()方法

我有延伸的ModelForm和使用用戶配置作爲其模型我自己的用戶登記表BaseCreationForm。所有的驗證方法工作正常,但保存方法讓我感到悲傷。每當我嘗試創建一個用戶(配置文件在視圖中創建,我可能會重構這個),Django會告訴我「BaseCreationForm對象沒有屬性清理數據」。但是,當出於挫折感和想法用盡時,我在save()方法中創建用戶之前添加了一個簡單的「打印自我」聲明,問題消失並且用戶正在正常創建。下面是幾個乾淨的()方法的工作,保存()方法,並從視圖中調用清理()一個片斷和save()方法。

乾淨()方法通常

#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) 

回答

4

你不應該重新實例化form_valid方法中的表單。這在表單已經有效時調用,並且表單確實傳遞給方法。您應該使用它。

(請注意,實際的錯誤是因爲你沒有叫form.is_valid()可言,但正如我上面說的你不應該的,因爲視圖已經在做了。)

+0

哦,我知道了,謝謝。它在那裏的原因是,我是上傳文件,並做麻煩較早和一些消息來源說我應該確保它包括(self.request.FILES)。但一定是錯誤的其他地方,因爲因爲現在,我只是評論出來它仍然有效。 – MikkoP

相關問題