How to allow users to change their own passwords in Django?
Can any one point me to code where users can change their own passwords in Django?
Django comes with a user authentication system. It handles user accounts, groups, permissions and cookie-based user sessions. This document explains how things work.
How to change Django passwords
See the Changing passwords section
Navigation to your project where
manage.py
file lies$ python manage.py shell
type below scripts :
from django.contrib.auth.models import User u = User.objects.get(username__exact='john') u.set_password('new password') u.save()
You can also use the simple manage.py
command:
manage.py changepassword *username*
Just enter the new password twice.
from the Changing passwords section in the docs.
If you have the django.contrib.admin
in your INSTALLED_APPS
, you can visit: example.com/path-to-admin/password_change/
which will have a form to confirm your old password and enter the new password twice.
You can also just use the django.contrib.auth.views.password_change
view in your URLconf. It uses a default form and template; supplying your own is optional.
Its without need to go to shell enter passwd and reenter passwd
python manage.py changepassword <username>
or
/manage.py changepassword <username>
Using shell
python manage.py shell
from django.contrib.auth.models import User
users=User.objects.filter(email='<user_email>')
#you can user username or etc to get users query set
#you can also use get method to get users
user=users[0]
user.set_password('__enter passwd__')
user.save()
exit()
This tutorial shows how to do it with function based views:
View file:
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.shortcuts import render, redirect
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(request.user, request.POST)
if form.is_valid():
user = form.save()
update_session_auth_hash(request, user) # Important!
messages.success(request, 'Your password was successfully updated!')
return redirect('change_password')
else:
messages.error(request, 'Please correct the error below.')
else:
form = PasswordChangeForm(request.user)
return render(request, 'accounts/change_password.html', {
'form': form
})
Url file:
from django.conf.urls import url
from myproject.accounts import views
urlpatterns = [
url(r'^password/$', views.change_password, name='change_password'),
]
And finally, the template:
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Save changes</button>
</form>
urls.py
:
urlpatterns = [
url(r'^accounts/', include('django.contrib.auth.urls')),
Template:
<a href="{% url 'password_change' %}">{% trans "Change password" %}</a>
Documented at: https://docs.djangoproject.com/en/1.9/topics/auth/default/#using-the-views