0

表格.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')

视图.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 表单方法,但仍然得到同样的错误,请帮助,在此先感谢。

4

2 回答 2

0

在清理之前,您在表单上调用 save 。你打电话 save 两次。在表单开始时保存一次。最后一次。

pform.is_valid() 返回一个您从不检查的布尔值。

modelforms 上的文档

于 2012-08-26T22:56:06.297 回答
0

表单没有验证,因为我在我的 UserProfileForm 元类中使用了“用户名”,而它不应该存在。

于 2012-08-27T00:28:06.527 回答