Django,使用ModelForm更新用户配置文件 [英] Django, updating a user profile with a ModelForm

查看:112
本文介绍了Django,使用ModelForm更新用户配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为用户的配置文件显示一个简单的ModelForm,并允许用户对其进行更新。这里的问题是我的逻辑是有缺陷的,并且在成功的form.save()调用之后,旧的值显示在页面上。直到刷新才显示适当的值。这里有什么问题?

I'm trying to display a simple ModelForm for a user's profile and allow the user to update it. The problem here is that my logic is somehow flawed, and after a successful form.save() call, the old values show on the page. It isn't until a refresh that the appropriate value is shown. What is wrong here?

@login_required
def user_profile(request):
    success = False
    user = User.objects.get(pk=request.user.id)
    upform = UserProfileForm(instance=user.get_profile())   

    if request.method == 'POST':
        userprofile = UserProfileForm(request.POST, instance=user.get_profile())
        if userprofile.is_valid():
            up = userprofile.save(commit=False)
            up.user = request.user
            up.save()
            success = True

    return render_to_response('profile/index.html',
        locals(), context_instance=RequestContext(request))

我只是想更新一个现有的配置文件,而不是添加一个新的。

I'm just looking to update an existing profile, not add a new one.

推荐答案

尝试这样:

@login_required
def user_profile(request):
    success = False
    user = User.objects.get(pk=request.user.id)
    if request.method == 'POST':
        upform = UserProfileForm(request.POST, instance=user.get_profile())
        if upform.is_valid():
            up = upform.save(commit=False)
            up.user = request.user
            up.save()
            success = True
    else:
        upform = UserProfileForm(instance=user.get_profile())       

    return render_to_response('profile/index.html',
        locals(), context_instance=RequestContext(request))

这篇关于Django,使用ModelForm更新用户配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆