Django forms always failing - django

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/

Related

How to update User password in django

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")

Django LDAP: Why my customized login doesn't work with LDAP while the default LoginView does?

I use ldap to authenticate users. A user logs in with the default Django LoginView and in the back ldap does all the checks and it works. However, if instead I customize my own login method with authentication, it no longer works. I know my login method is correct because it works in applications without ldap. So I wonder what is the problem... When I log in I always get "Incorrect password / username. Try again", which means that user is None after authentication...why?
Please check below the codes.
1)This is my customized method in views.py:
def login_page(request):
login_data = LoginForm()
return render(request, 'login.html', {'login_data':login_data})
def login_validate(request):
login_data = LoginForm(request.POST)
if login_data.is_valid():
user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])
if user is not None:
if user.is_active:
auth.login(request, user)
return redirect('/')
error_message= 'Incorrect password / username. Try again.'
return render(request, 'login.html', {'login_data':login_data,'login_errors':error_message})
error_message= 'Internal error. Please contact the administrator.'
return render(request, 'login.html', {'login_data':login_data,'login_errors':error_message})
It doesn't work with ldap... however if instead I choose
2)Default login:
def login(request):
return LoginView.as_view(template_name='login.html')(request)
it works with ldap ...both work in applications without ldap..so what is wrong in my code... I don't show the ldap set up but is the default one of django-ldap. What makes LoginView special in this case? If there are differences, then how do I customize my own login to behave identical like LoginView? Thanks

unable to implement basic login in the django framework

I am trying as hard as I can to learn to concept of authentication within the Django framework. I am reading the documentation and trying to code similar which will help me get the subject. At the moment I am trying to implement a simple login which redirects to a page. If the user is logged in he should see a message other wise he should see a different message. This is my code.
I have made a simple login form
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput())
this is my login view
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/users/success/')
else:
return redirect('/users/success/')
else:
form = LoginForm()
return render(request, 'testauth/login.html', {'form': form})
(I know the above code is a little bit redundant ... at the moment this is not so important)
and this is the success view
def success_view(request):
print(request.user)
if request.user.is_authenticated:
return HttpResponse("logged in")
else:
return HttpResponse("you are not logged in")
The problem is, I always get the "logged in" message even with users which do not exist. I tried restarting the server my cache is disabled ... I have no idea why is this happening. Why is this happening?
(p.s. I do not want to set in the settings.py a login success url. I want to do everything manually because I am struggling a lot with this topic and I want to make sure that I truly understand everything)

l can't login with the method l used, l have tried to use the authenticate method but it's not working can someone point me in the right direction

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.

How to resolve form resubmission?

When page refresh that post request, form resubmission happened.
I tried redirect after post request. but, it's not working when request have context. this context have form.errors because login.html show form error.
How to resolve this issue? (without Message Framework)
def do_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = authenticate(email=email, password=password)
if user is not None:
login(request, user)
return redirect(reverse('root'))
else:
pass
# redirect cannot pass context, right?
else:
form = LoginForm()
context = {
'form': form
}
return render(request, 'accounts/login.html', context=context)
Your code is using the standard approach. You are redirecting after a successful post request, but not after an unsuccessful post. This allows the form to be displayed with errors.
If the user refreshes after an unsuccessful post, then the browser will usually warn the user that their data will be resubmitted. If they do resubmit, then it doesn't really matter, the login will fail again, and they will see the same errors as before.