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
Related
what is the error with set_password
/base/backends.py in authenticate
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class CaseInsensitiveModelBackend(ModelBackend):
def authenticate(self,request,username=None,password=None,**Kwargs):
UserModel=get_user_model()
if username is None:
username=Kwargs.get(UserModel.USERNAME_FIELD)
try:
case_insensitive_username_field='{}__iexact'.format(UserModel.USERNAME_FIELD)
user = UserModel._default_manager.get(**{case_insensitive_username_field:username})
except UserModel.DoesNotExist:
UserModel().set_paassword(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
i try to put make_password but not working
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.
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')
Hello to Stack Overflow community,
I had created login and logout functions in django views.py hence i had successfully achieved login and logout methods also but i am confusing know that how can i pass data of this logged in user details to my class based views in views.py because i want to give access to my class based views only if user login happened
views.py
def admin_login(request):
context = {}
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user:
login(request, user)
context['user'] = request.user
return redirect('profile')
else:
context['error'] = 'Provide Valid Credentials'
return render(request, "secret_template.html", context)
else:
return render(request, "secret_template.html", context)
def admin_logout(request):
logout(request)
return redirect('secretview')
i want to authenticate below view only if user logged in
class index(TemplateView):
template_name = 'secret_template.html'
Use the LoginRequiredMixin in your view.
from django.contrib.auth.mixins import LoginRequiredMixin
class index(LoginRequiredMixin, TemplateView):
login_url = reverse_lazy('admin_login') # or whatever
template_name = 'aapp/index.html'
Following Django documentation you'll find some generic examples fitting your request:
For function based views you can simply use the login_required decorator.
from django.contrib.auth.decorators import login_required
#login_required
def my_view(request):
return Something
For class based views you have an example with method_decorator
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
#method_decorator(login_required, name='dispatch')
class ProtectedView(TemplateView):
template_name = 'secret.html'
edit:
I cannot comment, so I add this here:
You can handle a user instance from request.user inside your views methods.
forms.py:
from django import forms
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.utils.text import capfirst
from .models import Classname, Sectionname, Teachername, Attendancename
class AuthenticationForm(forms.Form):
username = forms.CharField(max_length=20)
password = forms.CharField(widget=forms.PasswordInput)
error_messages = {
'invalid_login': ("Please enter a correct %(username)s and password."
"Note that both fields may be case-sensitive."),
'inactive': ("This account is inactive"),
}
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username and password:
self.user_cache = authenticate(username=username, password=password)
if self.user_cache is None:
raise forms.ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
)
else:
self.confirm_login_allowed(self.user_cache)
return self.cleaned_data
def confirm_login_allowed(self, user):
if user.is_active:
login(self.user) /** It raises error here... **/
else:
raise forms.ValidationError(
self.error_messages['inactive'],
code='inactive',
)
def get_user_id(self):
if self.user_cache:
return self.user_cache.id
return None
def get_user(self):
return self.user_cache
views.py:
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.template.response import TemplateResponse
from django.views.generic import DeleteView, ListView
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.cache import never_cache
from .models import Classname, Sectionname, Teachername, Attendancename
from .forms import ClassnameForm, SectionnameForm, TeachernameForm, AttendancenameForm, UserForm, PasswordChangeForm, AuthenticationForm
def user_login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse('student:mains'))
else:
print(form.errors)
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form': form},)
urls.py:
from django.conf.urls import url, patterns
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', views.user_logout, name='logout'),
url(r'^password_change/$', auth_views.password_change, {'template_name': 'password_change_form.html', 'post_change_redirect': '/stu/password_change/done/'}, name="password_change"),
url(r'^password_change/done/$', auth_views.password_change_done, {'template_name': 'password_change_done.html'}, name="password_change_done"),
url(r'^restricted/', views.restricted, name='restricted'),
url(r'^mains/', views.mains, name = 'mains'),
]
I'm new to django authentication. I'm trying to make things as per the docs I have read. As your see above I've a 'user_login' view and 'AuthenticationForm' form.
I'm tring to login the user, but don't know the way how to do it? As I tried it in my view but didn't worked.
Then I tried it in my 'can_login_allowed' form's method but doesn't work.
Is there any other method to implement it?
Please! Can Anybody help me to fix it?
Thanks in Advance....
The login function takes request as first parameter. So you have write confirm_login_allowed like this:
def confirm_login_allowed(self, request):
if self.user_cache.is_active:
login(request,self.user_cache)
else:
raise forms.ValidationError(
self.error_messages['inactive'],
code='inactive',
)
And call it in the view like this
def user_login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
form.confirm_login_allowed(request)
return HttpResponseRedirect(reverse('student:mains'))
else:
....
Also don't call the confirm_login_allowed method from clean method because it does't have the request.