Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update User object without creating new one?

Following works fine in 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'

Then I try to do the same with forms:

# 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>

I open page in browser and see two fields First name and Last name. When I fill in the fields and submit the form I get the error:

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

I also tried to add ['username'] to fields list in UserForm. If I submit the form with my username (as request.user), the form displays errormessage:

User with this Username already exists.

If I change the username to some unique name, the new user with that username is being created.

The question is: How can I update User object, not create new one?

Sorry for being so verbose, but I had hard search here and could not find the answer to my question.

BTW, these cases don't work for me:

  • Extending UserCreationForm to include email, first name, and last name
  • add field first_name and last_name in django-profile
  • How to create a UserProfile form in Django with first_name, last_name modifications?

EDIT:

As suggested @fceruti I just added on request.method == 'post' branch this:

form = UserForm(data=request.POST, instance=request.user)
like image 330
Vlad T. Avatar asked Mar 31 '12 15:03

Vlad T.


People also ask

How do I update a specific field in Django?

Use update_fields in save() If you would like to explicitly mention only those columns that you want to be updated, you can do so using the update_fields parameter while calling the save() method. You can also choose to update multiple columns by passing more field names in the update_fields list.


2 Answers

Just add on request.method == 'post' branch this:

form = UserForm(data=request.POST, instance=request.user)
like image 50
fceruti Avatar answered Oct 19 '22 21:10

fceruti


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)
        ...
like image 25
Timmy O'Mahony Avatar answered Oct 19 '22 20:10

Timmy O'Mahony