我如何在django 1.7中获得用户个人资料

时间:2015-02-02 10:32:02

标签: python django

我想获取用户个人资料的每个细节。我知道函数get_profile()已被折旧。

我想获取用户个人资料,然后将其作为上下文传递给模板。

实际上我正在制作“编辑用户个人资料”功能。

我的模特:

class UserProfile(models.Model):
    user = models.OneToOneField(User)

    state = models.CharField(max_length=200, blank=True)
    country = models.CharField(max_length=200, blank=True)
    zipcode = models.CharField(max_length=200, blank=True)

观点:

@login_required
def dashboard(request):
    context = RequestContext(request)

    profile = request.user.userprofile

    context_dict = {'profile': profile}

    return render_to_response('appname/dashboard.html', context_dict, context)

1 个答案:

答案 0 :(得分:1)

要编辑UserProfile实例,您必须使用两种形式:

class UserForm(forms.ModelForm):
    class Meta:
        class = User
        fields = ('username', 'first_name', 'last_name')

class ProfileForm(forms.ModelForm):
    class Meta:
        class = UserProfile
        exclude = ('user', )

@login_required
def edit_profile(request):
    user = request.user
    profile = user.userprofile
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=user)
        profile_form = ProfileForm(request.POST, instance=profile)
        if all([user_form.is_valid(), profile_form.is_valid()]):
            user_form.save()
            profile_form.save()
            return redirect('.')
    else:
        user_form = UserForm(instance=user)
        profile_form = ProfileForm(instance=profile)
    return render(request, 'user_profile.html',
                       {'user_form': user_form, 'profile_form': profile_form})

模板应该在单个<form>标记中包含两种形式:

<form action="." method="POST">
    {% csrf_token %}
    {{ user_form.as_p }}
    {{ profile_form.as_p }}
    <button>Update</button>
</form>