i am trying to add to my messages.success the username so when he login the message go up and have the username
views.py:
def login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if username and password:
user = authenticate(username=username, password=password)
if user is not None:
l_login(request, user)
success_url = '/home'
messages.success(request, 'You logged in to ')
return redirect('home')
else:
messages.error(request, 'Username or Password is Incorrect')
else:
messages.error(request, 'Fill out all the Fields Please')
return render(request, 'register/login.html',{})
You can obtain this from the user object:
messages.success(request, f'You logged in to {user.username}')
The f'…' is literal string interpolation [pep-498].
Related
I am developing a feature, when a user registers it automatically logs the user in
but i get 'AnonymousUser' object has no attribute '_meta' error.
but when i use the same code to login the user it works fine.
my forms.py:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from .models import *
class RegisterForm(forms.Form):
fname = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"fname entry", "placeholder":"First Name"}), required=True)
lname = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"lname entry", "placeholder":"Last Name"}), required=True)
phone = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"phone entry", "placeholder":"Phone Number"}), required=True)
password = forms.CharField(widget=forms.PasswordInput(attrs={"class":"password entry", "placeholder":"Password", "autocomplete":"off"}), required=True)
password2 = forms.CharField(widget=forms.PasswordInput(attrs={"class":"password entry", "placeholder":"Confirm Password", "autocomplete":"off"}), required=True)
def clean(self, *args, **kwargs):
fname = self.cleaned_data.get("fname")
lname = self.cleaned_data.get("lname")
phone = self.cleaned_data.get("phone")
password = self.cleaned_data.get("password")
password2 = self.cleaned_data.get("password2")
if phone and password and fname and lname and password2:
try:
user = User.objects.get(phone=PhoneNumber.objects.get(number=phone))
if user:
raise forms.ValidationError("user exists login instead")
except ObjectDoesNotExist:
pass
if password!=password2:
raise forms.ValidationError("passwords didn't match")
else:
if len(password)<8:
raise forms.ValidationError("short password! password should be longer than 8")
in my forms i have a registration form which does not inherit from django's user creation form.
my views.py:
def registerView(request):
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
fname = form.cleaned_data.get("fname")
lname = form.cleaned_data.get("lname")
username = generate_username(fname, lname)
phone = form.cleaned_data.get("phone")
u = User.objects.create_user(email="", first_name=fname, last_name=lname, username=username, is_active=False)
u.set_password(form.cleaned_data.get("password"))
u.save()
p = PhoneNumber(user=u, number=phone)
p.save()
phone = PhoneNumber.objects.get(number=phone)
u = User.objects.get(phone=phone)
userLogin = authenticate(username=username, password=u.password)
login(request, userLogin)
return redirect('home')
else:
form = RegisterForm()
return render(request, 'main/register.html', {'form':form})
my loginView:
def loginView(request):
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
phone = PhoneNumber.objects.get(number=form.cleaned_data.get('phone'))
u = User.objects.get(phone=phone)
user = authenticate(username=u.username, password=form.cleaned_data.get('password'))
login(request, user, backend='django.contrib.auth.backends.ModelBackend')
print('success')
return redirect('home')
else:
form = LoginForm()
return render(request, 'main/login.html', {'form':form})
i have imported everything i need. the same code works with the loginView function but it doesn't work on registerView
What should i do to fix this?
You have this line in your view:
userLogin = authenticate(username=username, password=u.password)
The point to be noted here is that u is an instance of the user model and u.password will give the hashed password while authenticate expects it to be a raw password and hence returns None. In fact you don't even need to use authenticate while registering as you already have the user instance:
def registerView(request):
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
fname = form.cleaned_data.get("fname")
lname = form.cleaned_data.get("lname")
username = generate_username(fname, lname)
phone = form.cleaned_data.get("phone")
# removed `is_active=False` as per comment by #Nahu Gere
user = User.objects.create_user(email="", first_name=fname, last_name=lname, username=username) # better variable name
user.set_password(form.cleaned_data.get("password"))
user.save()
phone = PhoneNumber(user=user, number=phone)
phone.save()
login(request, user) # Directly use saved user instance
return redirect('home')
else:
form = RegisterForm()
return render(request, 'main/register.html', {'form':form})
I got this error because In my register view, I had this code:
user.is_active = False
user.save()
then I had so the user got logged in automatically after registering an account.
user = authenticate(username=user.username, password=raw_password)
login(request, user)
I solved it by commenting out the auto login
# user = authenticate(username=user.username, password=raw_password)
# login(request, user)
def loginUser(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('pass1')
user = authenticate(username, password)
if user is not None:
login(request, user)
return redirect( '/')
else:
messages.error(request, "Either your email or password is wrong!")
return render(request, 'loginpage.html')
return render(request, 'loginpage.html')
Whenever I enter the credentials on the login page this error appears, my login function is also named loginUser yet
You need to pass the credentials as named parameters:
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('pass1')
user = authenticate(username=username, password=password)
# …
I'm newbie to Django. I'm stuck at one thing that, my login authenticate method return None. I've tried my best to search and try to solve this but i didn't find my problem solution.
In Following First Code Sample From Which I Got Error,
`def loginAdmin(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('/admin-dashboard')
else:
messages.info(request, 'invalid')
else:
return HttpResponse('No')
# return render(request,'login.html') `
I'm getting value of form and using variable in authenticate method but its giving me that error. But in Following Second Code Sample That Execute Successfully
`
def loginAdmin(request):
if request.method == "POST":
username = request.POST['username'],
password = request.POST['password'],
user = auth.authenticate(username = 'user1', password = 'pass123')
if user is not None:
auth.login(request, user)
return redirect('/admin-dashboard')
else:
messages.info(request, 'invalid')
else:
return HttpResponse('No')
# return render(request,'login.html')
` if, I used hard coded value in authenticate method that i know saved in database username and password, then it will execute successful. I've debug form username and password They are coming.
I tried to elaborate my problem. Please guide me how to solve this.
Thank You.
Screen Shot 1 Link: Having error in This
Screen Shot 2 Link: But No error if Hard Coded Value
Please remove the trailing commas from the username and password.
username = request.POST['username']
password = request.POST['password']
When you use a comma like this: elem = 2, in Python, you make it a tuple (2,), instead of a string that the authenticate function in your code requires.
def loginAdmin(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('/admin-dashboard')
else:
messages.info(request, 'invalid')
return redirect('/login')
else:
return HttpResponse('No')
Or You Can Write Like This:
from django.contrib.auth import authenticate, login
from django.http import HttpResponse, HttpResponseRedirect
def loginAdmin(request):
if request.method == 'POST':
username = request.POST.get('username', None)
password = request.POST.get('password', None)
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.success(request, 'Welcome Back')
return HttpResponseRedirect(reverse('admin-dashboard'))
else:
messages.warning(request, 'Invalid Credentials')
return HttpResponseRedirect(reverse('login'))
else:
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('admin-dashboard'))
return render(request, 'dashboard/login.html')
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
username = request.POST['username']
password = request.POST['password']
user = authenticate(username = username, password = password)
I have hashed password (using set_password) in my database table , I want to compare the hashed-password with my plain password using check_password to login successfully.
views.py/login view
def logauth(request):
if request.method == "POST":
email = request.POST['username']
password = request.POST['password']
user = authenticate(request, email=email, password=password)
if user is not None:
messages.error(request, 'if part : user is not None')
login(request, user)
return redirect('emp')
else:
messages.error(request, 'else part : user is None')
return redirect('login_url')
else:
messages.error(request, 'Please provide valid credentials')
return render(request, 'registration/login.html')
backends.py
class MyBackEnd(object):
def authenticate(self, request, email=None, password=None):
existing_user = RegAuth.objects.get(email=email,password=password)
if not existing_user:
# Checking the user Regauth Custom DB.
user_data = RegAuth.objects.get(email=email,password=password)
if email == user_data.email:
user = RegAuth.objects.create_user(email=email, password=password)
user.save()
return user
else:
return None
else:
return existing_user
def get_user(self, email):
try:
return RegAuth.objects.get(email=email)
except Exception as e:
return False
I tried to check by printing where could be the cause of the problem. It shows that user_id and password were there but it cannot proceed after that.
def login_request(request):
if request.method == 'POST':
user_id = request.POST['user_id']
password = request.POST['password']
user = authenticate(user_id=user_id, password=password)
if user is not None:
login(request, user)
return redirect("/index")
else:
messages.info(request, 'Invalid Credentials')
return redirect('login_request')
else:
return render(request, 'login.html')
urls.py
path('login_request/', views.login_request, name='login_request'),
You need to authenticate user with username and password not with user_id
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request,username=username, password=password)
if user is not None:
login(request, user)
return redirect("/index")
else:
messages.info(request, 'Invalid Credentials')
return redirect('login_request')
else:
return render(request, 'login.html')