I'm having trouble when i try to update user password in django.
def password(request):
if request.method=="POST":
password =request.user.password
username=request.user.username
c_password=request.POST["current_password"]
new_password=request.POST["new_password"]
r_new_password=request.POST["retype_new_password"]
if password==c_password:
if new_password==r_new_password:
user =User.objects.get(username=username)
user.set_password(new_password)
user.save()
messages.info(request,"Successfully saved")
else:
messages.info(request,"PASSWORD DOES NOT MATCH")
else:
messages.info(request,"PASSWORD INCORRECT")
return render(request,"security.html")
When i fill the current password, it is giving me error password incorrect. But, when i fill pbkdf2_sha256$320000$Cb4s4nwqKwirdgo50ZdjLH$aeuSP3X+dSZXsv0XJB0XxkpwfsmU+PedMX9Jl50Zark=
, my password becomes correct and user password is updateable. My problem is I would like to fill in current password field as normal current password without getting the error.
You use authenticate(…) [Django-doc] to validate the password: this will retrieve the hashing algorithm and the salt, and check if the hashes match, so you can work with:
def password(request):
if request.method == 'POST':
c_password = request.POST['current_password']
new_password = request.POST['new_password']
r_new_password = request.POST['retype_new_password']
user = authenticate(username=request.user.username, password=c_password)
if user is not None:
if new_password == r_new_password:
user.set_password(new_password)
user.save()
messages.info(request, 'Successfully saved')
else:
messages.info(request, 'PASSWORDS DOE NOT MATCH')
else:
messages.info(request, 'PASSWORD INCORRECT')
return render(request, 'security.html')
There is however a PasswordChangeView [Django-doc] to change the password: this already implements the logic and uses a form. You can inject a different template, for example with:
path(
'password/change/',
PasswordChangeView.as_view(template_name='security.html'),
name='password_change'
)
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
Note: It is better to use a Form [Django-doc]
than to perform manual validation and cleaning of the data. A Form will not
only simplify rendering a form in HTML, but it also makes it more convenient
to validate the input, and clean the data to a more convenient type.
Refer the Documentation Django does not store raw (plain text) passwords on the user model
use authenticate function instead of using if password==c_password:.
from django.contrib.auth import authenticate
def password(request):
if request.method=="POST":
password =request.user.password
username=request.user.username
c_password=request.POST["current_password"]
new_password=request.POST["new_password"]
r_new_password=request.POST["retype_new_password"]
user = authenticate(username=username, password=c_password)
if user is not None:
if new_password==r_new_password:
user =User.objects.get(username=username)
user.set_password(new_password)
user.save()
messages.info(request,"Successfully saved")
else:
messages.info(request,"PASSWORD DOES NOT MATCH")
else:
messages.info(request,"PASSWORD INCORRECT")
return render(request,"security.html")
Related
def index(request):
#check if username and password POST requests exits (user submitted form)
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(request,username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('home')
else:
messages.info(request, "invalid credentials")
return redirect('index')
else:
return render(request, 'index.html')
here is my code l even tried to just use authentication without the auth but same results
Normally Django's authenticate will check if the hashed version of the password matches with the stored password. Therefore you can not save the password in a raw manner.
The AbstractBaseUser class therefore offers a set_password(…) method [Django-doc] that will set the password to the hashed form of the password.
You thus can implement this as:
# …
else:
user.set_password(user.password)
user.save()
messages.info(request,"Registered Successfully")
I would furthermore strongly advise to use a Form (or a ModelForm) to validate the input data. This is in fact the main task of a Form: to validate and clean input, and remove a lot of boilerplate code with respect to validation error messages, cleaning, and saving the object.
I am working on a sign in page in Django, but I am using Userena. I have attached the view method for the signin in Userena below. The problem is that since all the views I have written previously to this were MUCH shorter and concise. I'm having trouble trying to figure out where in this method I would add something in to "do something if password is wrong". Ideally, what I would like to do is if the password is wrong, trigger a popup in javascript. I'm guessing I first have to add something to this view method that indicates the password is wrong though?
#secure_required
def signin(request, auth_form=AuthenticationForm,
template_name='userena/signin_form.html',
redirect_field_name=REDIRECT_FIELD_NAME,
redirect_signin_function=signin_redirect, extra_context=None):
form = auth_form()
if request.method == 'POST':
form = auth_form(request.POST, request.FILES)
if form.is_valid():
identification, password, remember_me = (form.cleaned_data['identification'],
form.cleaned_data['password'],
form.cleaned_data['remember_me'])
user = authenticate(identification=identification,
password=password)
if user.is_active:
login(request, user)
if remember_me:
request.session.set_expiry(userena_settings.USERENA_REMEMBER_ME_DAYS[1] * 86400)
else: request.session.set_expiry(0)
if userena_settings.USERENA_USE_MESSAGES:
messages.success(request, _('You have been signed in.'),
fail_silently=True)
#send a signal that a user has signed in
userena_signals.account_signin.send(sender=None, user=user)
# Whereto now?
redirect_to = redirect_signin_function(
request.REQUEST.get(redirect_field_name), user)
return HttpResponseRedirect(redirect_to)
else:
return redirect(reverse('userena_disabled',
kwargs={'username': user.username}))
if not extra_context: extra_context = dict()
extra_context.update({
'form': form,
'next': request.REQUEST.get(redirect_field_name),
})
return ExtraContextTemplateView.as_view(template_name=template_name,
extra_context=extra_context)(request)
check user present or not like :
if user:
if user.is_active:
login(request,user)
else:
# account disabled
else:
#invalid login detailed
return response
Im a bit new to django and working on the user handling.
Now have i sorted it all and it works just fine, except for when a user enters faulthy data to login.
No errormessage is shown.
I was wondering if there would be a easier/better approach to fix this then putting a empty variable in all my views, except the invalid login. (to store the message in)
My auth_view:
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
#returns None if not correct
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect(reverse('index'))
else:
invalid_login = "ErrorMessage"
return HttpResponseRedirect(reverse('index')
index is just this at the moment:
def index(request):
return render(request, 'index.html')
How can i solve this? (or would you suggest i just approach it with the extra var everywhere)
With kind regards
Hans
Here is how i solved it:
def index(request):
"""Logs a user into the application."""
auth_form = AuthenticationForm(None, request.POST or None)
# The form itself handles authentication and checking to make sure passowrd and such are supplied.
if auth_form.is_valid():
login(request, auth_form.get_user())
return HttpResponseRedirect(reverse('index'))
return render(request, 'index.html', {'auth_form': auth_form}
Now problem is my style class from css doesnt seem to work anymore.
But well we are getting there
(used the UserAuthenticationForm here
I've view like this. It worked. I'm new to django. Can you please help me to improve this code? thank you
def getAPI(request):
username = request.GET.get('username')
password = request.GET.get('password')
#TODO Match user and password
if username:
user = User.objects.get(username__exact=username)
is_exist = user.check_password(password)
if is_exist == True:
api_key = ApiKey.objects.get(id=user.id)
else:
error_message = 'username or password is invalid.'
return render_to_response('details.html',locals(),
context_instance=RequestContext(request)
)
if username and password does not exist Then I want to print error message. Otherwise I want to print ApiKey. thanks
Do you mean "print" (in which case just use python's print function) or do you want to return it in the response? If the latter, read up about django templates and passing variables to render_to_response.
Also, sticking a password as a GET variable is a bit of a bad idea, since it'll be visible on the URL:
http://example.com/whatever?username=me&password=s3cr3t
User/pass info should normally be sent via POST from a form. But maybe you're not that bothered about security.
Here's the basic template to authenticate a user:
from django.contrib.auth import authenticate
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
# User is authenticated - return api key
else:
# Return a 'disabled account' error message
else:
# Return an 'invalid login' error message.
I'm trying to use Django's built in authentication modules. For the site I'm working on I want to use email addresses as login names and not just the normal alphanumeric fields they're usually set to. In order to do this I changed all the String fields to Email fields and changed their max length from 30 to 320. My registration code appears to be working fine but not my login code. Here is what I'm using right now:
def login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
return HttpResponse("valid")
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect("/")
# Redirect to a success page.
else:
return HttpResponse("Disabled Account")
# Return a 'disabled account' error message
else:
return HttpResponse("Invalid Login")
# Return an 'invalid login' error message.
else:
return HttpResponse("%s" % repr(form.errors))
else:
form = AuthenticationForm()
return render_to_response("login.html", {'form': form, }, context_instance=RequestContext(request))
No matter what I submit, form.is_valid() is returning FALSE but form.errors is empty. Any ideas what might be wrong? I think I changed everything over to Email properties so I don't think that's it. Also, in case it changes anything I'm trying to do this on google app engine using djangoappengine.
Sorry, but you cannot use Django's authentication module on top of google app engine. Django uses its own special database backend which is similar to google-app-engine's but is not drop-in compatible.
If you want to do authentication on GAE, you should do it the google-app-engine way:
http://code.google.com/appengine/docs/python/users/