0

视图.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():
                user = pform.save()

                return redirect(profile,nav="account")
            else:
                context['data'] ={'nav_menu': ['account','profile','reviews','favourites'],
                'cur_nav':nav}
                context['pform'] = pform
                context['rform'] = PartialSignupForm()
                context['lform'] = LoginForm()
                context['aform']  = AccountsForm()
                return render_to_response(template,context,context_instance = RequestContext(request))
        else:
            return redirect(profile,nav="profile")


    else:
        context['rform'] = PartialSignupForm()
        context['lform'] = LoginForm()
        context['aform']  = AccountsForm()

        context['pform'] = UserProfileForm(instance = request.user)
        context['data'] ={'nav_menu': ['account','profile','reviews','favourites'],
               'cur_nav':nav}
        context['reviews'] = request.user.review_set.all()
        if extra_context is not None:
            context.update(extra_context)
        return render_to_response(template,context,context_instance = RequestContext(request))

表格.py

class UserProfileForm(forms.ModelForm):
    sex = forms.CharField(max_length = 20,label="I am :",widget=forms.Select(choices=SEX_CHOICES,attrs = {'class':''}),required = False)
    first_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Please enter your real name.','class':''}),required = False)
    last_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter last name.','class':''}),required = False)
    location = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter your current location','class':''}),required = False)
    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 clean_phone(self):
        phone = self.cleaned_data['phone']
        if phone == '':
            raise forms.ValidationError("This field is required.")
        return phone

    def clean_last_name(self):
        last_name = self.cleaned_data['last_name']
        if last_name == '':
            raise forms.ValidationError("This field is required.")
        return last_name

    def clean_profession(self):
        profession = self.cleaned_data['profession']
        if profession == "":
            raise forms.ValidationError("Select a valid option.")
        return profession

    def clean_sex(self):
        sex = self.cleaned_data['sex']
        if sex == "":
            raise forms.ValidationError("Select a valid option.")
        return sex
    def clean_location(self):
        location = self.cleaned_data['location']
        if location == "":
            raise forms.ValidationError("This field is required.")
        return location

    def __init__(self,*args,**kw):
        super(UserProfileForm,self).__init__(*args,**kw)
        self.phone = self.instance.get_profile().phone
        self.profession = self.instance.get_profile().profession
        self.sex = self.instance.get_profile().sex
        self.location = self.instance.get_profile().location        

    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")
        profile = self.instance.get_profile()
        profile.sex = self.cleaned_data.get("sex")
        profile.location = self.cleaned_data.get("location")
        profile.profession = self.cleaned_data.get("profession")
        profile.phone = self.cleaned_data.get("phone")
        profile.save()
        self.instance.save()
        return self.instance

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

模型.py

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    phone = models.CharField(max_length = 40,blank=False,default = "")
    location = models.CharField(max_length = 100,blank=False,default = "")
    sex = models.CharField(max_length =  10,blank = False,default = "")
    profession = models.CharField(max_length =  50,blank = False,default = "")

怀疑

我无法理解,当我呈现要编辑的配置文件表单时,只有名字和姓氏在那里,但是当我填写详细信息并提交表单时,它对用户配置文件进行了更改,但重新加载配置文件表单不是使用 userprofile 表单的值启动的,只设置了 first_name 和 last_name 值,我知道该表单是用户模型表单,但是当我使用用户配置文件值启动它时,我没有得到预期的结果,请帮助,在此先感谢。

4

2 回答 2

2

UserProfileForm,

class Meta:
   model = User

需要更改为

class Meta:
   model = UserProfile
于 2012-08-27T22:38:27.723 回答
1

正如 Karthikr 所说,您的表单正在加载来自用户模型(名字/姓氏)的值,而不是来自用户配置文件的值。如果您希望出现正确的值,则需要根据正确的模型(在本例中为 UserProfile)启动表单。

于 2013-06-28T19:28:29.820 回答