Check user submitted password in database - python

I'm new in Django programming and I'm stuck in this problem.
This is the code that I have in views.py:
def login(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
else:
context = RequestContext(request, {})
return render(request, 'login.html', context)
How can I search the user that have the email inserted in the html form, and check if the password is correct?
Thanks in advance for your help.

Try this:
def login(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
# Assuming the fields in your `User` model are labeled the same
user = authenticate(email=email, password=password)
else:
context = RequestContext(request, {})
return render(request, 'login.html', context)

Related

I want to make a staff user by default

I am making a library system with signup pages (admin and user), so when I make an admin user I want to make it in staff, so how can I use (is_staff)?
this is my registration function...
def register(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, 'Account created successfully')
return redirect(loginpage)
context = {'form':form}
return render(request, 'pages/register.html', context)
You can alter the .instance wrapped in the form before saving it to the database:
def register(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.instance.is_staff = True
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, 'Account created successfully')
return redirect(loginpage)
return render(request, 'pages/register.html', {'form':form})

Django forms is_valid() for registration, always false

I'm still learning django and I'm trying to create a register and login page.
I beleive i created the form right, and the .is_valid() looks good to me also, I have no idea what i did wrong.
every time I submit the register form, it fails and renders the else condition, same with the login function, even thought I went into admin to add a user manually.
my user model is called 'Users'
Forms:
class reg_form(forms.Form):
username = forms.CharField(label='username', max_length=64)
password = forms.CharField(widget=forms.PasswordInput)
email = forms.EmailField(label="email", max_length=64)
phone = forms.CharField(label='Phone', max_length=64)
first_name = forms.CharField(label='First Name', max_length=64)
last_name = forms.CharField(label='Last Name', max_length=64)
class log_form(forms.Form):
username = forms.CharField(label='username', max_length=64)
password = forms.CharField(widget=forms.PasswordInput)
Register:
def register(request):
if request.method == 'POST':
form = reg_form(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
phone = form.cleaned_data['phone']
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
user = Users.objects.Create(username=username, email=email, password=password, phone=phone, first_name=first_name, last_name=last_name)
Users.save(user)
login(request, user)
return render(request, 'profile.html')
else:
return render(request, 'register.html', {
'form': reg_form
})
else:
return render(request, 'register.html', {
'form': reg_form
})
login:
def log_in(request):
if request.method == 'POST':
form = log_form(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 render(request, 'profile.html')
else:
return render(request, 'login.html', {
'form2': log_form
})
else:
return render(request, 'login.html', {
'form2': log_form
})
else:
return render(request, 'login.html', {
'form2': log_form
})
To see the errors you should return Bound Form:
def register(request):
if request.method == 'POST':
form = reg_form(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
email = form.cleaned_data.get'email')
phone = form.cleaned_data.get('phone')
first_name = form.cleaned_data.get('first_name')
last_name = form.cleaned_data.get('last_name')
user = Users.objects.create(
username=username, email=email,
password=password, phone=phone,
first_name=first_name, last_name=last_name
)
login(request, user)
return render(request, 'profile.html')
else:
return render(request, 'register.html', {
# If the form not valid return bound form
'form': form
})
else:
return render(request, 'register.html', {
'form': reg_form
})
And do the same in your log_in view.
I suggest you to use ModelForm.
Also see Coding style (Django Docs):
Use InitialCaps for class names (or for factory functions that return
classes).
Field names should be all lowercase, using underscores instead of
camelCase.

How to extend default user model in django2.12

I am working on a project and i am not using the default django user model instead i am using my own custom user model. but i am experiencing a problem. For my user model i have also made my own authb.py file which i have provided below and if i am using the default django authentication then it is authenticating only my superuser and not the user that i am entering through the sign up form and i am totally stuck.
first here is my authb.py
from .models import User
class AuthB:
def authenticate(self, username=None, password=None):
try:
user = User.objects.get(username=username)
return user
except:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except:
return None
but right now i am not using this authb instead i am using default authentication.
here is my models.py for user model
class User(models.Model):
is_authenticated = True
username = models.CharField(max_length= 25)
email = models.CharField(max_length= 150)
password = models.CharField(max_length= 100)
last_login = models.DateTimeField(auto_now= True)
profilepic = models.CharField(max_length= 255, default= "")
def __str__(self):
return self.username
here is my views.py file
def signup(request):
# context = {}
# return render(request, 'sign-up.html', context)
if request.method == 'POST':
# print(request.POST)
# Get form values
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
# Check if passwords match
# Check Username
if User.objects.filter(username=username).exists():
return redirect('signup')
else:
if User.objects.filter(email=email).exists():
return redirect('signup')
else:
u = User.objects.create_user(username=username, password=password, email=email)
u.save()
return redirect('login')
else:
return render(request, 'sign-up.html')
def login(request):
# context = {}
# return render(request, 'index.html', context)
if request.method =='POST':
# print(request.POST)
email = request.POST['email']
password = request.POST['password']
u= auth.authenticate(email=email, password=password)
return redirect('index')
else:
return render(request, 'login.html')
The main problem is that simple user is not able to login in my website only admin are able to login and django i not authenticating my simple user.

I want to make sign in & up for my site with Django but it doesn't work

form.py
class SignUpForm(forms.Form):
name = forms.CharField(max_length=50, required=True)
email = forms.EmailField(max_length=100, required=True)
password = forms.CharField(max_length=20, required=True)
class SignInForm(forms.Form):
email = forms.EmailField()
password = forms.CharField(max_length=20, min_length=8)
view.py
def Sign_Up(request.POST):
if request.method == 'POST':
form = SignUpForm(request)
if form.is_valid():
cd = form.cleaned_data
name = cd['name']
email = cd['email']
password = cd['password']
us = User..objects.get(email__exact=email, password__exact=password)
return HttpResponseRedirect('/')
else:
form = SignUpForm()
return render(request,'User Login Page.html', {'form':form})
def Sign_In(request.POST):
if request.method =='POST' :
form = SignInForm(request)
if form.is_valid():
F = form.cleaned_data
Eemail = F['email']
Epassword = F['password']
try:
user = User.objects.filter(email=Eemail)
except User.DoesNotExist:
form = SignInForm()
return render(request, "Admin Login Page.html", {'form': form})
if User.password == Epassword:
return HttpResponseRedirect("/")
form = SignInForm()
return render(request,"Admin Login Page.html",{'form':form})
I want to make a sign in & up for my site with Django but it doesn't work!
When I click on the submit button my sign up directly goes to the HttpRsponseDirect address even with empty parameters
def Sign_Up(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
name = cd['name']
email = cd['email']
password = cd['password']
user = form.save()
user.refresh_from_db()
user.save()
user = authenticate(username=email, password=password)
return HttpResponseRedirect('/')
else:
form = SignUpForm()
return render(request,'signup.html', {'form':form})
def Sign_In(request):
if request.method =='POST' :
form = SignInForm(request)
if form.is_valid():
F = form.cleaned_data
Eemail = F['email']
Epassword = F['password']
user=authenticate(username=F,password=Epassword)
if user is not None:
return HttpResponseRedirect("/")
else:
form=SignInForm()
message='login failed'
retuen render(request,'login.html',{'form':form,'message':message})
look at upside code
Unless you have multiple security experts on the job; please, please, please let someone else handle your logins like Google or Facebook. like when you go to create account it says "use google to sign in"

Django request.user becomes anonymous after redirect

In my Django app I create a User from django.contrib.auth.models, and I am using request.user in multiple view functions without a problem. In one of my view functions I change the user password, save the user, and redirect the client to another view function. Once I try to get the user from the request in that function, the user is Anonymous. After using User.set_password() or redirecting, does it take the user out of the session ?
views.py
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from .models import Profile
from .forms import ProfileForm, PasswordForm
def sign_in(request):
form = AuthenticationForm()
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
if form.user_cache is not None:
user = form.user_cache
if user.is_active:
login(request, user)
return HttpResponseRedirect(
reverse('home') # TODO: go to profile
)
else:
messages.error(
request,
"That user account has been disabled."
)
else:
messages.error(
request,
"Username or password is incorrect."
)
return render(request, 'accounts/sign_in.html', {'form': form})
def sign_up(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(data=request.POST)
if form.is_valid():
form.save()
user = authenticate(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1']
)
new_profile = Profile.objects.create(user=user)
login(request, user)
messages.success(
request,
"You're now a user! You've been signed in, too."
)
return HttpResponseRedirect(reverse('home')) # TODO: go to profile
return render(request, 'accounts/sign_up.html', {'form': form})
def sign_out(request):
logout(request)
messages.success(request, "You've been signed out. Come back soon!")
return HttpResponseRedirect(reverse('home'))
def profile(request):
user = request.user
try:
account = Profile.objects.get(user=user)
except Profile.DoesNotExist:
account = None
print(account.first_name)
context = {'account': account}
return render(request, 'accounts/profile.html', context)
def edit(request):
account = Profile.objects.get(user=request.user)
form = ProfileForm(instance=account)
if request.method == 'POST':
account = Profile.objects.get(user=request.user)
form = ProfileForm(request.POST, request.FILES)
if form.is_valid():
account.first_name = form.cleaned_data['first_name']
account.last_name = form.cleaned_data['last_name']
account.email = form.cleaned_data['email']
account.bio = form.cleaned_data['bio']
account.avatar = form.cleaned_data['avatar']
account.year_of_birth = form.cleaned_data['year_of_birth']
account.save()
context = {'account': account}
return HttpResponseRedirect('/accounts/profile')
else:
x =form.errors
context = {'form': form, 'errors': form.errors}
return render(request, 'accounts/edit.html', context)
else:
context = {'form': form}
return render(request, 'accounts/edit.html', context)
def change_password(request):
user = request.user
if request.method == 'POST':
form = PasswordForm(request.POST)
if form.is_valid():
cleaned_data = form.cleaned_data
if not user.check_password(cleaned_data['old_password']):
form.add_error('old_password', 'Old password is incorrect')
context = {'form': form}
return render(request, 'accounts/password.html', context)
try:
user.set_password(cleaned_data['new_password'])
user.save()
return HttpResponseRedirect('/accounts/profile')
except Exception as e:
form = PasswordForm()
context = {'form': form}
return render(request, 'accounts/password.html', context)
else:
form = PasswordForm()
context = {'form': form}
return render(request, 'accounts/password.html', context)
forms.py
class PasswordForm(forms.Form):
old_password = forms.CharField(max_length=200)
new_password = forms.CharField(max_length=200)
confirm_password = forms.CharField(max_length=200)
def clean(self, *args, **kwargs):
cleaned_data = super(PasswordForm, self).clean()
if 'new_password' in cleaned_data:
new_password = cleaned_data['new_password']
else:
new_password = None
if 'confirm_password' in cleaned_data:
confirm_password = cleaned_data['confirm_password']
else:
confirm_password = None
if confirm_password and new_password:
if new_password != confirm_password:
self.add_error('confirm_password', 'Passwords do not match')
Yes. See the documentation about session invalidation on password change. To fix it, see this bit in particular:
The default password change views included with Django, PasswordChangeView and the user_change_password view in the django.contrib.auth admin, update the session with the new password hash so that a user changing their own password won't log themselves out. If you have a custom password change view and wish to have similar behavior, use the update_session_auth_hash() function.

Categories

Resources