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.
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>
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()
urls.py:
urlpatterns = [
url(r'^accounts/', include('django.contrib.auth.urls')),
Template:
{% trans "Change password" %}
Documented at: https://docs.djangoproject.com/en/1.9/topics/auth/default/#using-the-views
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.
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")
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.
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()"
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:
Change Password
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'),
Related
I am working on a django project and I am using the default auth app for authentication.
I know that there is a last_login field in user model which stores the user's last login time.
When a staff user logs in first time into the admin panel, I want to check if last_login field is none & redirect him to the change password page.
Where should I put this check?
What I have tried so far:
I have tried to use a custom login form and override the default confirm_login_allowed method on it, but it seems like I can only raise a validation error to block login attempt using these.
I also tried using django.contrib.auth.signals.user_logged_in Signal but that also does not allow me to return a redirect response when last_login is None.
I want to know how I can return a redirect response after the user has been authenticated.
Customise Django admin using AdminSite and use login_form attribute to give the custom login form for the Admin login page.
admin.py
class MyAdminSite(AdminSite):
login_form = CustomAdminLoginForm
admin_site = MyAdminSite(name='myadmin')
admin_site.register(User)
admin_site.register(Group
urls.py
When overriding the Admin we have to get rid of Django default admin
from app.admin import admin_site
url(r'^admin/', admin_site.urls)
forms.py
AuthenticationForm have the confirm_login_allowed method use this to grant permission to login in or not login in.
class CustomAdminLoginForm(AuthenticationForm):
def confirm_login_allowed(self, user):
if user.last_login:
raise ValidationError(mark_safe('Hey first time user please reset your password here... test'), code='inactive')
Note: There is lot of edge cases you have to consider for this approach.
What if user not set the password in the first time and how you're going to handle second attempt..? This time last_long not None. Although date_joined comes rescue. last_login == date_joined
But What if the user not set the password in first day and comes next day ?
Edit:
You can use signal to check the logged in user and apply the config_login_allowed logic here...?
from django.contrib.auth.signals import user_logged_in
def change_password_first_time(sender, user, request, **kwargs):
# Your business logic here...
user_logged_in.connect(change_password_first_time)
Django admin is not that configurable. You should hook into its internal views. Login/logout views are inside Django AdminSite class (the one you usually access by admin.site). My implementation is a bit hacky but small:
Paste at the top of urls.py
from django.contrib import admin
from django.contrib.admin import AdminSite
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
class MyAdminSite(AdminSite):
def login(self, request, extra_context=None):
new_user = False
user = None
username = request.POST.get('username') # Hack to find user before its last_login set to now.
if username:
user = User.objects.filter(username=username).first()
if user:
new_user = user.last_login is None
r = super(MyAdminSite, self).login(request, extra_context)
if new_user and request.user == user and isinstance(r, HttpResponseRedirect): # Successful logins will result in a redirect.
return HttpResponseRedirect(reverse('admin:password_change'))
return r
admin.site = MyAdminSite()
If you want a cleaner solution I suggest to use a boolean inside user model instead of relying on last_login so you could just check request.user instead of my hack into request.POST.
You could read AdminSite.login and django.contrib.auth.views.login to see what is actually happening inside Django.
It was a big problem for me at once. I found a way to do it easy. Create a different variable to save the value of the users logged in data, when user is trying to login.
Below is my code:
if user.last_login is None:
auth.login(request,user)
return redirect(alertPassword)
# when user is login for the first time it will pass a value
else:
auth.login(request,user)
return redirect(moveToLogin)
def moveToLogin(request):
return render(request,"home.html")
def alertPassword(request):
first_login=True
return render(request,"home.html",{"first_login":first_login})
#it will pass a value to the template called first login is True
Then go to your template and add this:
{% if first_login==True%}
# Put anything you want to be done
# In my case I wanted to open a new window by using script.
<script>
window.open("popUpWindow")
</script>
{%endif%}
Actually i'am very new to django and python. In /templates/home.html, added {{ user.username }} it's showing currently logged in username
<p>Welcome {{ user.username }} !!!</p>
I want to get currently logged in username in views.py file. How to get username?
i tried different way but i am not get the result
user = User.objects.get(username=request.user.username)
username = request.GET['username']
def sample_view(request):
current_user = request.user
print(current_user)
Please tell me, How to achieve my result.
my views.py look like this. is there any problem on my views.py
#!python
#log/views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.template import Context
from contextlib import contextmanager
# Create your views here.
# this login required decorator is to not allow to any
# view without authenticating
#login_required(login_url="login/")
def home(request):
return render(request,"home.html")
#dummy_user = {{ username }}
#user = User.objects.get(username=request.user.username)
#username = request.GET['username']
#print(usernam
#user = request.user
#print(user)
def sample_view(request):
current_user = {}
#current_user['loggeduser'] = request.user
#or
current_user['loggeduser'] = request.user.username
return render(request,"home.html",current_user)
# print(current_user.id)
Provided that you have enabled the authentication middleware, you don't need to do any of this. The fact that the username shows up in your template indicates that you have enabled it. Each view has access to a request.user that is an instance of a User model. So the following is very much redundant
user = User.objects.get(username=request.user.username)
Because you already have request.user.username!! if you wanted to find the user's email, you do request.user.email Or just do
user = request.user
and use the newly created variable (eg user.username)
Reference: https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.user
From the AuthenticationMiddleware: An instance of AUTH_USER_MODEL
representing the currently logged-in user. If the user isn’t currently
logged in, user will be set to an instance of AnonymousUser. You can
tell them apart with is_authenticated, like so:
I have a custom Django login page. I want to throw an exception when username or password fields are empty. How can I do that?
My view.py log in method :
def user_login(request):
context = RequestContext(request)
if request.method == 'POST':
# Gather the username and password provided by the user.
# This information is obtained from the login form.
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
print("auth",str(authenticate(username=username, password=password)))
if user:
# Is the account active? It could have been disabled.
if user.is_active:
login(request, user)
return HttpResponseRedirect('/')
else:
return HttpResponse("xxx.")
else:
# Bad login details were provided. So we can't log the user in.
print ("Invalid login details: {0}, {1}".format(username, password))
return HttpResponse("Invalid login details supplied.")
else:
return render_to_response('user/profile.html', {}, context)
I tried this and it didn't work:
This is forms.py
def clean_username(self):
username = self.cleaned_data.get('username')
if not username:
raise forms.ValidationError('username does not exist.')
You can use login view, which is provided by Django. So your login.html should look like that example.
<form class="login" method="POST" action="/login/">
{% csrf_token %}
{{form.as_p}}
<li><input type="submit" class="logBut" value="Log in"/></li>
</form>
And remember urls.py !
url(r'^login/$','django.contrib.auth.views.login', {'template_name': '/login.html'}),
The correct approach is to use forms, instead of fetching the variables directly from request.POST. Django will then validate the form data, and display errors when the form is rendered in the template. If a form field is required, then Django will automatically display an error when the field is empty, you don't even need to write a clean_<field_name> method for this.
Django already has a built in login view. The easiest approach is to use this rather than writing your own. If you still want to write your own view, you will still find it useful to look at how Django does it.
Hello! I'm having trouble with the authentication system. I've followed the documentation pretty closely, but I just can't seem to get this to work. The problem seems to be that when I call the authenticate method with my cleaned form data, it's not returning anything. It's clearly doing this in the web page (it just returns the render request at the bottom every time I submit the form), and I tried authenticating in the same way via the shell and am also returning True for 'user is None'.
I'm wondering if perhaps the problem is that I haven't included the proper middleware? My MIDDLEWARE_CLASSES are as follows:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
It appears that I have everything necessary, but I'm just not sure.
In any case, here's the code for my view:
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import authenticate, login
def user_login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse("Good Job")
else:
return HttpResponse("Inactive User")
else:
return HttpResponse("Bad Job")
else:
form = AuthenticationForm()
return render(request, 'myapp/login_form.html', {
'form': form,
})
And here is my very simple login_form.html template:
<h1>Login</h1>
<form action="/login/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
UPDATE: I have implemented the following solution:
changed the line
form = AuthenticationForm(request.POST)
to
form = AuthenticationForm(data = request.POST)
Now I am able to login via the superuser account, but username/password combinations for ordinary accounts are not recognized. If I submit the credentials for a regular user, the form is re-rendered plus the following message:
Please enter a correct username and password. Note that both fields may be case-sensitive.
Any ideas?
UPDATE 2
It turns out I had an error in my registration form such that it wasn't properly storing the password for new users registered via that form. I was doing password assignment in the constructor for a new User object, when instead you need to:
User.objects.create_user('username', 'email', 'password')
Rookie mistake! Thanks for the help.
Try form = AuthenticationForm(data = request.POST)
From the django git for AuthenticationForm:
def __init__(self, request=None, *args, **kwargs):
"""The 'request' parameter is set for custom auth use by subclasses.
The form data comes in via the standard 'data' kwarg.`
"""
I have a database and have the admin interface enabled. When I go to the admin interface and click on 'Users' there is one user whose username is ayman. I am following a tutorial done in a book called 'Packt Publishing, Learning Website Development with Django'. Now, in my urls.py, this is what I have.
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', main_page),
url(r'^user/(\w+)/$', user_page),
)
In my views.py, this is my user_page
def user_page(request, username):
try:
user = User.objects.get(username=username)
except:
raise Http404(username +' not found.')
bookmarks = user.bookmark_set.all()
variables = {
'username': username,
'bookmarks': bookmarks
}
return render(request, 'user_page.html', variables)
I am using the generic User view to manage my users. When I go into the terminal and do
$python manage.py shell
and do
>>> from django.contrib.auth.models import User
>>> from bookmarks.models import *
>>> user = User.objects.get(id=1)
>>> user
<User: ayman>
>>> user.username
u'ayman'
as you can see, the username ayman Does exist. Now, going back to the URLs and the user_page view. In my web browser, I went to
127.0.0.1/user/ayman/
The urls.py should capture ayman and pass it as a parameter to user_page, right? It does, but the user_page view keeps raising the 404 error and it says ayman not found. So the username parameter in user_page is in fact ayman but it keeps failing the
user = User.objects.get(username=username)
even though ayman is a username in my database. Any idea why?
You are using a bare except clause, try except User.DoesNotExist. The bare except masks the real error, the missing import. Btw. there is also a shortcut for this:
from django.shortcuts import get_object_or_404
# ...
user = get_object_or_404(User, username=username)
The first argument is the model or a queryset, the following are all passed as keyword arguments to queryset.get()