178π
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.
27π
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.
- [Django]-How to use permission_required decorators on django class-based views
- [Django]-How do you dynamically hide form fields in Django?
- [Django]-How to update() a single model instance retrieved by get() on Django ORM?
8π
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>
- [Django]-Change a field in a Django REST Framework ModelSerializer based on the request type?
- [Django]-Django, Turbo Gears, Web2Py, which is better for what?
- [Django]-Django unit tests without a db
5π
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()
- [Django]-Django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
- [Django]-Django β filtering on foreign key properties
- [Django]-Django apps aren't loaded yet when using asgi
3π
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
- [Django]-Celery : Execute task after a specific time gap
- [Django]-How to override and extend basic Django admin templates?
- [Django]-Django queries β id vs pk
2π
Per the documentation, use:
from django.contrib.auth.hashers import makepassword
The main reason to do this is that Django uses hashed passwords to store in the database.
password=make_password(password,hasher='default')
obj=User.objects.filter(empid=emp_id).update(username=username,password=password)
I used this technique for the custom user model which is derived from the AbstractUser
model. I am sorry if I technically misspelled the class and subclass, but the technique worked well.
- [Django]-How can I get all the request headers in Django?
- [Django]-Django switching, for a block of code, switch the language so translations are done in one language
- [Django]-How can I call a custom Django manage.py command directly from a test driver?
2π
Authentication is the one way and after that reset the password
from django.contrib.auth import authenticate
user = authenticate(username='username',password='passwd')
try:
if user is not None:
user.set_password('new password')
else:
print('user is not exist')
except:
print("do something here")
- [Django]-Django β Circular model import issue
- [Django]-Passing STATIC_URL to file javascript with django
- [Django]-Why does django run everything twice?
1π
Once the url pattern is added as shown in Ciro Santilliβs answer, a quick way to allow users to change passwords is to give them βstaff accessβ for the admin functions. If you donβt add them to any groups or give them special permissions, they can still change their password by going to the example.com/admin page. The staff access lets them go to the page even if it is blank; in the upper right corner they can click βchange passwordβ and use the admin funtionality.
- [Django]-Django TypeError: 'RelatedManager' object is not iterable
- [Django]-Difference between filter with multiple arguments and chain filter in django
- [Django]-How to change field name in Django REST Framework
1π
This is the command i used, just in case you are having problem in that throw AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User'
.
python manage.py shell -c "from django.contrib.auth import get_user_model;
User = get_user_model();
u = User.objects.get(username='admin');
u.set_password('password123');
u.save()"
- [Django]-Disabled field is not passed through β workaround needed
- [Django]-Delete multiple objects in django
- [Django]-How to send email via Django?
0π
Very similar to @Ciroβs answer, but more specific to the original question (without adding all the authentication views):
just add to urlpatterns
in urls.py
:
url('^change-password/$', auth_views.password_change, {'post_change_redirect': 'next_page'}, name='password_change'),
Note that post_change_redirect
specifies the url to redirect after the password is changed.
Then, just add to your template:
<a href="{% url 'password_change' %}">Change Password</a>
- [Django]-How to resize the new uploaded images using PIL before saving?
- [Django]-How to check whether the user is anonymous or not in Django?
- [Django]-Django auto_now and auto_now_add
-1π
view.py
views.py
def changepassword(request):
if request.method == "POST":
user_id = request.POST['user_id']
oldpassword = request.POST['oldpassword']
newpassword = request.POST['newpassword']
user = User.objects.get(id=user_id)
if **user.check_password**(oldpassword):
**user.set_password(newpassword)**
user.save()
return redirect("app:login-user")
else:
messages.success(request,"Pervious Password Not Match")
return redirect("app:changepassword")
else:
return render(request,'app/changepassword.html')
url.py
path('changepassword',views.changepassword,name='changepassword'),
- [Django]-Django REST Framework β 405 METHOD NOT ALLOWED using SimpleRouter
- [Django]-Django Form File Field disappears on form error
- [Django]-Auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'