Django: User not authenticating correctly - django

When logging into my app, the user is not authenticating correctly.
Views.py
'''
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login
from django.urls import reverse
from users.forms import CustomUserCreationForm
from django.http import HttpResponse
from users.models import Blog
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.decorators import login_required
# Create your views here.
def intro(request):
return render(request, "intro.html")
def logmein(request):
return render(request, "logmein.html")
def login(request):
username1 = request.POST.get('username')
password1 = request.POST.get('password')
user = authenticate(request, username=username1, password=password1)
login(user, request)
if user.is_authenticated:
return render(request, "users/mainmenu.html")
else:
return render(request, "intro.html")
def mainmenu(request):
return render(request, "users/mainmenu.html")
'''
Mainmenu.html
'''
{% extends 'base.html' %}
{% block content %}
<h2>MainMenu</h2>
Hello, {{ user.username }}
{% endblock %}
'''
When mainmenu.html is displayed following login, the user.username is showing as the SuperUser, regardless
of what username and password is used to login.

try this:
from django.contrib.auth import login as auth_login
def login(request):
username1 = request.POST.get('username')
password1 = request.POST.get('password')
user = authenticate(username=username, password=password)
if not user: # authentication fails
messages.error(request, 'error')
return render(request, "intro.html")
# login success
auth_login(request, user)
messages.success(request, 'success')
return render(request, "users/mainmenu.html")

Related

after pressing verification link ... nothing happens in Django .. user still unverified

Views.py(name of app: userprofileinfo)
from django.shortcuts import render
from userprofileinfo.forms import UserForm
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.csrf import csrf_exempt,csrf_protect
from django.views import View
from django.contrib import messages
from django.core.mail import send_mail
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text, DjangoUnicodeDecodeError
from django.core.mail import send_mail
from django.contrib.sites.shortcuts import get_current_site
from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode
from django.template.loader import render_to_string
from .utils import account_activation_token
from django.urls import reverse
from django.contrib import auth
#login_required
def special(request):
return HttpResponseRedirect("You are logged in, Nice!")
#login_required
def userlogout(request):
logout(request)
return HttpResponseRedirect(reverse('careforallapp:base'))
def register(request):
registered = False
if request.method == "POST":
user_form = UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.is_active = False
user.save()
email = UserForm('email')
current_site = get_current_site(request)
email_body = {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
}
link = reverse('userprofileinfo:activate', kwargs={
'uidb64': email_body['uid'], 'token': email_body['token']})
email_subject = 'Activate your account'
activate_url = 'http://'+current_site.domain+link
send_mail(
email_subject,
'Hi '+user.username + ', Please the link below to activate your account \n'+activate_url,
'settings.EMAIL_HOST',
[user.email],
fail_silently=False
)
return HttpResponseRedirect(reverse('careforallapp:base'))
else:
print(user_form.errors)
else:
user_form = UserForm()
return render(request,'userprofileinfo/registration.html',
{'user_form':user_form,
'registered':registered})
class VerificationView(View):
def get(self, request, uidb64, token):
try:
id = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=id)
if not account_activation_token.check_token(user, token):
return redirect('login'+'?message='+'User already activated')
if user.is_active:
return redirect('login')
user.is_active = True
user.save()
messages.success(request, 'Account activated successfully')
return redirect('login')
except Exception as ex:
pass
return HttpResponseRedirect(reverse('userprofileinfo:userlogin'))
def userlogin(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username = username, password = password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('careforallapp:base'))
else:
return HttpResponse("ACCOUNT NOT ACTIVE")
else:
print("Someone tried to login and failed!")
print("Username: {} and password: {}".format(username, password))
return HttpResponse("invalid login details")
else:
return render(request, 'userprofileinfo/login.html', {})
.env
export EMAIL_HOST_PASSWORD=*******
export EMAIL_HOST_USER = careall249#gmail.com
export EMAIL_HOST=smtp.gmail.com
urls.py
from django.conf.urls import url
from django.urls import path
from .views import VerificationView
from userprofileinfo import views
app_name = 'userprofileinfo'
urlpatterns = [
url(r'^login/', views.userlogin, name='userlogin'),
url(r'^register/', views.register, name='register'),
url(r'^logout/', views.userlogout, name='userlogout'),
url(r'^special/', views.special, name='special'),
path('activate/<uidb64>/<token>', VerificationView.as_view(), name='activate'),
]
Can someone go through the code. Login page, registration page all working fine but verification link is not working, when user register, he gets the link on his Gmail but when he presses the link for verify nothing happens. User not get active. Can somebody go through it and find the error.

How to get individual users data after login in django?

iam new to django.Can anyone send me the code of signup and login page to get particular details of the username without using django.contrib.auth.models import User.
(i.e if we login with some usename then it should only give details of that username not remaining).
Find view you want manipulate user in, declare user like current_user = request.user. I will provide you my login and register views below. In examples shown below I had from django.contrib.auth.models import User, but you can modify it as shown above.
Register:
def registerPage(request):
if request.user.is_authenticated:
return redirect('todoapp:home')
else:
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
email = request.POST.get('email')
if form.is_valid():
if check_does_email_already_exist(email):
form.save()
messages.success(request, "User is registered sucessfully")
return redirect('todoapp:login')
else:
messages.warning(
request, "User with same email already exist")
else:
messages.warning(
request, "That username already exist or your password is too short")
context = {
'form': form,
}
return render(request, 'register.html', context)
Login:
def loginPage(request):
if request.user.is_authenticated:
return redirect('todoapp:home')
else:
if request.method == 'POST':
username = request.POST.get('uname')
password = request.POST.get('passwd')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('todoapp:home')
else:
messages.warning(
request, "Your password or username isn't valid")
return redirect('todoapp:login')
else:
pass
return render(request, 'login.html')
These are my imports:
from django.shortcuts import render, redirect
from django.urls import reverse
from django.utils import timezone
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import CreateUserForm
And this is my forms.py:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from django.forms import fields
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = [
'username',
'email',
'password1',
'password2',
]
I hope my answer will help you.

Error while entering the login form details based on signup form

I am trying to enter the details in login form.But it is not authenticating the username and password with the existing usernames and passwords present in form data.
Here is my code
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth import authenticate, login, logout
from . forms import signup_form,loginform,profileform
from . models import registration_form
def index(request):
return render(request,'loginapp/index.html')
def display_form(request):
rform = signup_form(request.POST)
if rform.is_valid():
rform.save()
return HttpResponseRedirect('/profile/')
else:
return render(request,'loginapp/first.html',{'rform': rform})
def login_form(request):
if request.method == 'POST':
Username = request.POST.get('Username')
Password = request.POST.get('Password')
registration_form=
authenticate(Username=Username,Password=Password)
print("Username")
if registration_form is None:
if registration_form.is_active:
login(request,registration_form)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Your account was inactive.")
else:
print("Someone tried to login and failed.")
print("They used Username: {} and Password:
{}".format(Username,Password))
return HttpResponse("Invalid login details given")
return HttpResponseRedirect('/profile/')
else:
return render(request, 'loginapp/login.html', {})
def profile_form(request):
return render(request,'loginapp/profile.html')

How to authenticate for login

How I can authenticate my user for login ,here authenticate does not work properly
I have used authenticate for login
views.py
from django.shortcuts import render
from basic_app.models import Signup
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
def signup(request):
if request.method=="POST":
obj=Signup()
obj.username=request.POST.get('username')
obj.password=request.POST.get('password')
obj.save()
context={'username':'username'}
return render(request,'basic_app/singup.html',context)
else:
return render(request,'basic_app/singup.html')
def login(request):
if request.method=="POST":
username=request.POST.get('username')
password=request.POST.get('password')
user=authenticate(username=username,password=password)
if user:
login(request,user)
return HttpResponse("you have login")
else:
return HttpResponse("wrong password or username")
else:
return render(request,'basic_app/login.html')
You should login using login after authenticating.
user = authenticate(username=request.POST.get('username',''),
password=request.POST.get('password',''))
login(request, user)
Read:https://docs.djangoproject.com/en/2.1/topics/auth/default/#how-to-log-a-user-in
Actually, you can use Django's inbuilt LoginView ("https://docs.djangoproject.com/en/2.1/topics/auth/default/#django.contrib.auth.views.LoginView")
If you want to change the layout style. Either override the Django login template or override the class view.
For overriding the class view:
from django.contrib.auth.views import LoginView
class MySignInView(LoginView):
form_class = MySignInForm
template_name = 'mylife/myrules/login.html'
I have edited your following code :
from django.shortcuts import render
from basic_app.models import Signup
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
def login(request):
if request.method=="POST":
username=request.POST.get('username')
password=request.POST.get('password')
user=authenticate(username=username,password=password)
if user:
login(request,user)
return HttpResponse("you have login")
else:
return HttpResponse("wrong password or username")
else:
return render(request,'basic_app/login.html')
1) When you authenticate your username and password, it just returns User and it doesn't make you to login,
2) for login you have to call login(requst,user),it will create session in your database as acknowledgment

Is there a example in django 1.6 and python 3 to build a accounts app (include:register , login , and logout )

I do have read the offical document, but it describes every facility separately, after reading
'User authentication in Django' ,'First steps' , 'The model layer', 'The view layer' and 'The template layer' and 'Forms' , I still donot know how to create a account system.
there seems no django 1.6 and python 3 built account app source code or tutorial. where can I get them, thanks.
update:
All I what is a account app which I can plug it into any new project. Its urls will look like this:
accounts/register (the form class of this page is created from the class User in django.contrib.auth)
accounts/login
accounts/logout
accounts/profile (the form class of this page is created from the model which has a field OneToOneField(User))
In your views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.core.context_processors import csrf
#Import a user registration form
from YourApp.forms import UserRegisterForm
# User Login View
def user_login(request):
if request.user.is_anonymous():
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
#This authenticates the user
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
#This logs him in
login(request, user)
else:
return HttpResponse("Not active")
else:
return HttpResponse("Wrong username/password")
return HttpResponseRedirect("/")
# User Logout View
def user_logout(request):
logout(request)
return HttpResponseRedirect('/')
# User Register View
def user_register(request):
if request.user.is_anonymous():
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid:
form.save()
return HttpResponse('User created succcessfully.')
else:
form = UserRegisterForm()
context = {}
context.update(csrf(request))
context['form'] = form
#Pass the context to a template
return render_to_response('register.html', context)
else:
return HttpResponseRedirect('/')
In your forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password1', 'password2')
In your urls.py:
# Accounts urls
url(r'accounts/login/$', 'YourApp.views.user_login'),
url(r'accounts/logout/$', 'YourApp.views.user_logout'),
url(r'accounts/register/$', 'YourApp.views.user_register'),
At last, in register.html:
<form action="/accounts/register/" method="POST"> {% csrf_token %}
<h2>Please enter your details . . .</h2>
{{ form.as_p }}
<input type="submit" value="Sign Up">
</form>
Hope this helps.