django使用modelform更新用户配置文件

时间:2012-08-27 19:05:53

标签: django django-forms

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():
                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))

forms.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')

models.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值,我知道表单是用户模型表单,但是当我使用用户配置文件值启动它时,我不知道预期结果,请提前帮助,谢谢。

2 个答案:

答案 0 :(得分:2)

UserProfileForm

class Meta:
   model = User

需要改为

class Meta:
   model = UserProfile

答案 1 :(得分:1)

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