jartymcfly
jartymcfly

Reputation: 1995

How can I change the username and the password of a user in django programatically?

I am creating an application in django and I have a user who can change the passwords and usernames of the other users.

In my views.py I have a view that controls this.

I get the user of a concrete username this way:

user = User.objects.get(username=user_name)
user.username = request.POST['username']

user.set_password(request.POST['password'])
user.save()

But when I save all, I see that the selected user's username didn´t changed.

How can I set the username and the password of the selected user "user_name"?

Thank you!

Upvotes: 1

Views: 278

Answers (1)

jartymcfly
jartymcfly

Reputation: 1995

I got it! It's too easy! If you want to change any value of a user object, you have to do this:

First, import the User model of Django like this:

from django.contrib.auth.models import User

Next, you have to get the user the information you want to change of:

user_to_change = User.objects.get(username=username)

Then, change the values:

user_to_change.set_password(request.POST['password'])
user_to_change.username = request.POST['username']
...

Finally, save the information changed:

user_to_change.save()

Hope this helps!

Upvotes: 1

Related Questions