2012-08-26 56 views
0

forms.py
class UserProfileForm(forms.ModelForm): 
    phone = forms.CharField(max_length = 15,widget = forms.TextInput(attrs = {'placeholder':'Enter mobile no. ','class':''})) 
    profession = forms.CharField(max_length= 50,widget = forms.Select(choices = PROFESSION_CHOICES,attrs = {'class':''})) 
    #email = forms.EmailField(label='Email address',max_length = 75,widget = forms.TextInput(attrs={'placeholder':'Email address.','class':''})) 
    sex = forms.CharField(max_length = 20,label="I am :",widget=forms.Select(choices=SEX_CHOICES,attrs = {'class':''})) 
    first_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Please enter your real name.','class':''})) 
    last_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter last name.','class':''})) 
    location = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter your current location','class':''})) 
    def clean_first_name(self): 
     first_name = self.cleaned_data['first_name'] 
     if first_name == '': 
      raise forms.ValidationError("This field is required.") 
     return first_name 

     def save(self,*args,**kw): 
        self.instance.first_name = self.cleaned_data.get("first_name") 
        self.instance.last_name = self.cleaned_data.get("last_name") 
        self.instance.sex = self.cleaned_data.get("sex") 
        self.instance.location = self.cleaned_data.get("location") 
        self.instance.profession = self.cleaned_data.get("profession") 
        self.instance.phone = self.cleaned_data.get("phone") 
        self.instance.save() 
        return self.instance 





    class Meta: 
     model = User 
     fields = ('username','first_name','last_name','phone','sex','profession','location') 

views.py
def profile(request,nav="profile",template="profile.html",context = {},extra_context = None): 
    if request.POST: 
     if 'profileFormSubmit' in request.POST: 
      pform = UserProfileForm(request.POST,instance = request.user) 
      if pform.is_valid(): 
       try: 
        user = pform.save() 
        return redirect(profile,nav="profile") 
        except RuntimeError as e: 
        return HttpResponse(e) 

誤差
The User could not be changed because the data didn't validate. 

user = super(UserProfileForm,self).save(*args,**kw) 

疑問

我應該做些什麼改變來擺脫這個錯誤 我該如何改變,我已經嘗試刪除所有的clean_field窗體方法,但仍然得到相同的錯誤,請幫助,謝謝提前。django的更新用戶簡檔形式

回答

0

形式沒有得到驗證,因爲我是在我的元級的UserProfileForm,這是不應該出現的使用「用戶名」。

+0

接受你的答案這樣的問題將無法保持開放。 – jdi

0

在清潔之前,您正在調用保存在窗體上。你要保存兩次。一旦在表單保存的開始。最後一次。

pform.is_valid()返回一個布爾值,你永遠不會檢查。

docs on modelforms

+0

我已經改變了一點,但還是我得到的錯誤UserProfileForm可是沒有一個cleaned_data屬性 – Abhimanyu

+0

cleaned_data不會存在,直到您驗證表單後。您必須檢查is_valid,或者直接調用clean方法。基本上你沒有先清理掉保存方法。 – jdi

+0

我已經單獨清洗所有的領域,如clean_first_name ...等。 ,但我仍然得到相同的錯誤 – Abhimanyu