After work, it works fine in the 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 the page in a browser and see two fields First name and Last name . When I fill in the fields and submit the form, I get an error message:
Exception Type: IntegrityError Exception Value: column username is not unique
I also tried adding ['username'] to the list of fields in UserForm. If I submit a form with my username (as request.user), an error message is displayed on the form:
User with this Username already exists.
If I change the username to some unique name, a new user will be created with that username.
Question: How to update a User object rather than create a new one?
Sorry to be so verbose, but I had a tough search here and could not find the answer to my question.
By the way, these cases do not work for me:
EDIT:
As suggested by @fceruti, I simply added this to the request.method == 'post' branch:
form = UserForm(data=request.POST, instance=request.user)