如何在不创建新对象的情况下更新User对象?

时间:2012-03-31 15:52:16

标签: django django-models django-forms

以下在shell中工作正常:

>>> from django.contrib.auth.models import User
>>> user=User.objects.get(pk=1)
>>> user.first_name = u'Some'
>>> user.last_name = u'Name'
>>> user.save()
>>> user.first_name
u'Some'
>>> user.last_name
u'Name'

然后我尝试对表单做同样的事情:

# forms.py
class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['first_name', 'last_name']


# views.py
def edit_names(request, template_name="registration/edit_names.html"):
    if request.method == "POST":
        form = UserForm(data=request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.save()
            url = urlresolvers.reverse('my_account')
            return HttpResponseRedirect(url)
    else:
        form = UserForm(instance=request.user)
    page_title = _('Edit user names')
    return render_to_response(template_name, locals(),
        context_instance=RequestContext(request))

# edit_names.html
<form action="." method="post">{% csrf_token %}
    <table>
        {{ form.as_table }}
        <tr><td colspan="2">
            <input type="submit" />
        </td></tr>
    </table>
</form>

我在浏览器中打开页面,看到两个字段First nameLast name。当我填写字段并提交表单时,我收到错误:

 Exception Type:    IntegrityError
Exception Value:    column username is not unique

我还尝试将['username']添加到UserForm中的字段列表中。如果我使用我的用户名(作为request.user)提交表单,表单将显示errormessage:

User with this Username already exists.

如果我将用户名更改为某个唯一名称,则会创建具有该用户名的新用户。

问题是: 如何更新用户对象,而不是创建新对象?

很抱歉这么冗长,但我在这里搜索过难以找不到问题的答案。

顺便说一下,这些案例对我不起作用:

修改

正如所建议@fceruti我刚刚在request.method =='post'分支上添加了这个:

form = UserForm(data=request.POST, instance=request.user)

2 个答案:

答案 0 :(得分:20)

只需添加request.method =='post'分支:

form = UserForm(data=request.POST, instance=request.user)

答案 1 :(得分:3)

if request.method == "POST":
    kwargs = { 'data' : request.POST }
    try:
        kwargs['instance'] = User.objects.get(username=request.POST['username'])
    except:
        pass
    form = UserForm(kwargs**)
    if form.is_valid():
        user = form.save(commit=False)
        ...