django更新用户个人资料表格

时间:2012-08-26 22:43:22

标签: django django-models django-forms

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表单方法,但仍然得到相同的错误,请帮助,提前感谢。

2 个答案:

答案 0 :(得分:0)

在清洁之前,您正在调用保存表单。你打电话给保存两次。一旦在表单保存开始。而且一旦到了最后。

pform.is_valid()返回一个你永远不会检查的布尔值。

docs on modelforms

答案 1 :(得分:0)

表单没有验证,因为我在UserProfileForm的元类中使用了'username',这不应该在那里。