how to login a user using forms? - django

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.

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.

The view account.views.signup didn't return an HttpResponse object. It returned None instead

Trying to register user in Django. it keep giving me HttpResponse error
signup.html templates location is : templates/registration/signup.html
Here's what i tried:
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
username = forms.CharField(max_length=50)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2', )
views.py
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect, HttpResponse
from django.contrib.auth.decorators import login_required
from .forms import SignUpForm
#login_required
def home(request):
return render(request, 'registration/home.html')
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
user = authenticate(email= email, password= raw_password)
login(request, user)
return redirect('registration/home')
else:
form = SignUpForm()
return render(request, 'registration/signup.html', {'form': form})
I did tried replacing redirect with HttpResponseRedirect but it did't work
Account urls.py
from django.contrib.auth import views as auth_views
from django.conf.urls import url
from django.urls import path
from . import views
urlpatterns = [
path("login/", auth_views.LoginView.as_view(template_name = "registration/login.html"), name='login'),
path("logout/", auth_views.LogoutView.as_view(), name='logout'),
path('home/', views.home, name='home'),
url('signup/', views.signup, name='signup'),
]
Error
ValueError at /accounts/signup/
The view account.views.signup didn't return an HttpResponse object. It returned None instead.
Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/signup/
Django Version: 3.0.3
Exception Type: ValueError
Exception Value:
The view account.views.signup didn't return an HttpResponse object. It returned None instead.
You need to support GET method e.g.:
def signup(request):
form = SignUpForm()
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
user = authenticate(email= email, password= raw_password)
login(request, user)
return redirect('registration/home')
return render(request, 'registration/signup.html', {'form': form})

redirect() not directing to proper view

I am trying to use the redirect() method redirect to my index view upon successful submission of the form found in my register view.
I have the following urls.py:
from django.contrib import admin
from django.urls import path
from users import views as usersViews
urlpatterns = [
path('admin/', admin.site.urls),
path('', usersViews.index, name = 'index'),
path('register/', usersViews.register, name = 'regsister'),
]
and the following views.py:
from django.shortcuts import render, redirect
from .forms import RegistrationForm
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse('signed up')
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save() # save form? to db?
username = form.cleaned_data.get('username')
email = form.cleaned_data.get('email')
return redirect("index") #this statement is not working
else:
form = RegistrationForm()
return render(request, 'users/registration.html', {'registrationForm':form})
Upon submission of the form I am being redirected to "/register/index.html" and not "/" (index page). Can anyone help with this?
Try it with reverse:
from django.urls import reverse
return redirect(reverse('app_name:view_name'), {'registrationForm':form})

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