Reputation: 1091
Is it possible to change the username?
I tried the following :-
user = User.objects.get(username = username)
user.username = newusername
user.save()
Nothing changes
I can change the username in the admin screen, but there are more than 100 where the client asked for different usernames to be used.
Upvotes: 9
Views: 23188
Reputation: 5095
Before changing the username, also make sure the username does not already exist:
if User.objects.filter(username=newusername).exists():
raise forms.ValidationError(u'Username "%s" is not available.' % newusername)
user = User.objects.get(username = username)
user.username = newusername
user.save()
Upvotes: 3
Reputation: 575
There is one more possible scenario why username does not change after save...
Your username in User object has default max length of 30 and you try to change the username to something longer than 30 chars and the first 30 chars of new and old username are the same ;)
Upvotes: 4
Reputation: 49886
As you note (Django, change username), this was a mistake in your code - the code sample did not reflect your code. The code sample posted will in fact work to change a User
object's username:
user = User.objects.get(username = username)
user.username = newusername
user.save()
Upvotes: 17