authenticate() function not working django.contrib.auth - python

I have a login_page function and in this function the authenticate() function returns a user object only if it is a superuser. For normal user, it returns None. Which is not as the documentation says.
def login_page(request):
if request.user.is_authenticated(): # if user is already logged in
return HttpResponseRedirect('/') # SHOULD BE DASHBOARD
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
seo_specialist = authenticate(username=username, password=password) #returns None
if seo_specialist is not None:
login(request, seo_specialist)
return HttpResponseRedirect('/') # SHOULD BE DASHBOARD
else:
return render(request, 'login.html', {'form': form})
else:
return render(request, 'login.html', {'form': form})
else:
form = LoginForm()
context = {'form': form}
return render(request, 'login.html', context)
Is there anything wrong with my code?

Try this:
def login_page(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
seo_specialist = authenticate(username=username, password=password)
if seo_specialist is not None:
return HttpResponse("Signed in")
else:
return HttpResponse("Not signed in")
else:
# takes you to sign in form.
Basically replace is_valid and cleaned_data with request.POST and then authenticate. Also make sure you have
from django.contrib.auth import authenticate
at the top of your views.

This is from django documentation. You seem to not have passed the request in ...authenticate(request, user...)
This example shows how you might use both authenticate() and login():
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
...
else:
# Return an 'invalid login' error message.
...

Related

How to fix ERR_TOO_MANY_REDIRECTS?

I'm developing a site on Django, but I got an error ERR_TOO_MANY_REDIRECTS. I think that the matter is in the views.py file. Help figure it out.
P.S. already tried to delete cookie files, it didn't help(
from email import message
from wsgiref.util import request_uri
from django.shortcuts import redirect, render
from django.contrib.auth.models import User, auth
from django.contrib import messages
# Create your views here.
def reg(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
cpassword = request.POST['cpassword']
if password == cpassword:
if User.objects.filter(username=username):
messages.info(request, 'Username taken')
return redirect('registration')
else:
user = User.objects.create_user(username=username, password=password)
user.save()
return redirect('login')
else:
messages.info(request, 'Passwords not matching')
return redirect('registration')
return redirect('/')
else:
return render(request, 'registration.html')
def login(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username = username, password = password)
if user is not None:
auth.login(request, user)
return redirect('/')
else:
messages.info(request, 'Invalid credentials')
return redirect('login')
else:
return render(request, 'login.html')
def logout(request):
auth.logout(request)
return redirect('/')
The problem is coming from your return redirect('/'). Redirect to one of the views written in your urls.py and your problem will be solved.

Why doesn't my form validation work in django?

I am trying to have user validation in my django social media/blog app. I do not understand why this code does not work. The problem: No matter what name I type in the form it says the user does not exist even though the user does in fact exist. Any help would be amazing.
from django.shortcuts import render, redirect
from sign_in.forms import SignInForm
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth.forms import forms
from django.http import HttpResponseRedirect
def sign_in(request):
if request.method == "POST":
form = SignInForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = User.objects.filter(username=username, password=password)
if user.exists():
return HttpResponseRedirect("boom/")
else:
messages.error(request, f"User {user} does not exist.")
else:
form = SignInForm()
return render(request, "sign_in/sign_in.html", {"form": form})
this is not how Django authentication works.
https://docs.djangoproject.com/en/3.1/topics/auth/
use authenticate method
try this
from django.contrib.auth import login, authenticate
def sign_in(request):
if request.method == "POST":
form = SignInForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(username=username, password=password)
login(request, user)
if user.exists():
return HttpResponseRedirect("boom/")
else:
messages.error(request, f"User {user} does not exist.")
else:
form = SignInForm()
return render(request, "sign_in/sign_in.html", {"form": form})

Problem with request.user.is_authenticated

I am writing a simple django view that takes username and password and authenticates it using authenticate(). However, after successful authentication, request.user.is_authenticated is still False.
Here is the code:
def login(request):
if request.method == 'POST':
form = loginform(request.POST)
if form.is_valid():
username = request.POST['USERNAME']
password = request.POST['PASSWORD']
user = authenticate(username=username, password=password)
if user is not None :
return HttpResponse(request.user.is_authenticated)
else :
return HttpResponse('Login Failed')
else:
form = loginform()
return(render(request,'signup/login.html'))
In my version of django, request.user.is_authenticated is a attribute not function.
from django.contrib.auth import authenticate, login
def login(request):
if request.method == 'POST':
form = loginform(request.POST)
if form.is_valid():
username = request.POST['USERNAME']
password = request.POST['PASSWORD']
user = authenticate(username=username, password=password)
if user is not None :
login(request, user)
return HttpResponse(request.user.is_authenticated)
else :
return HttpResponse('Login Failed')
else:
form = loginform()
return(render(request,'signup/login.html'))
after authenticate don't forget to login user with login(request, user) ,doc is here.

Creating login and logout class based views in Django 1.8

I am learning class based views in Django 1.8, and wondering if anyone could help me here. I have created a function based login and logout views as you can see below:
LOGIN
def Login(request):
if request.method == "POST":
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('/form')
else:
return HttpResponse("Inactive user.")
else:
return HttpResponseRedirect(settings.LOGIN_URL)
return render(request, "index.html")
LOGOUT
def Logout(request):
logout(request)
return HttpResponseRedirect(settings.LOGIN_URL)
Could anyone help me to convert these views into Class Based Views in Django? I am pretty new to this stuff, and couldn't understand properly how exactly they are working. Will appreciate any help!
Go through the documentation https://docs.djangoproject.com/en/1.8/topics/class-based-views/intro/#using-class-based-views
from django.views.generic import View
class LoginView(View):
def post(self, request):
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('/form')
else:
return HttpResponse("Inactive user.")
else:
return HttpResponseRedirect(settings.LOGIN_URL)
return render(request, "index.html")
class LogoutView(View):
def get(self, request):
logout(request)
return HttpResponseRedirect(settings.LOGIN_URL)

django registration/login views using #login_required decorator

I am trying to create a separate register view for user, but it doesn't work since I am using the #login_required decorator on my 'profile' view, which is should redirect to after signing in. Currently the login_user view works fine.
QUESTION: How can I register the user while using the #login_required decorator on 'profile' view?
My code looks like this for the login and registration view:
def login_user(request):
message = None
if request.method == 'POST':
if 'login' in request.POST:
form = AuthenticationForm(data=request.POST)
if form.is_valid():
user = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password'])
if not user:
message = "Invalid email or password!"
else:
login(request, user)
return redirect('profile')
return render(request, 'users/login.html', {'message': message})
def register_user(request):
message = None
if request.method == 'POST':
user_form = RegistrationForm(data=request.POST)
if user_form.is_valid():
user_form.save()
user = authenticate(username=user_form.cleaned_data['email'],
password=user_form.cleaned_data['password1'])
if user:
login(request, user)
return redirect('profile')
else:
message = "Email already exists or passwords do not match"
return render(request, 'users/register.html', {'message': message})
In order for my registration page to get around the #login_required decorator I used the login(request, user) method, but this doesn't seem to be working.
You have to mention the backend as a third argument to the login function.
So in your register_user function:
if user:
# specify the backend as the third argument
login(request, user, backend='django.contrib.auth.backends.ModelBackend')
return redirect('profile')

Categories

Resources