I placed a authentication before displaying a view but when i run it it give this error
TypeError:'bool' object is not callable
user.is_autheticated() not work in django 2.1.5
def Login_View(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['pwd']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
data_user = User.objects.get(username=request.user)
request.session['username'] = username
return render(request,'dashboard_app/index.html',{'data_user':data_user.username})
else:
return render(request, 'login_app/index.html', {'error_message': 'Your account has been disabled'})
else:
return render(request, 'login_app/index.html', {'error_message': 'Invalid login'})
return render(request, 'login_app/index.html')
def Dashboard_View(request):
if request.user.is_authenticated():
if request.session.has_key('username'):
name=request.session['username']
return render(request, "dashboard_app/index.html",{'name':name})
else:
request.session['username'] = User.username
else:
return render(request, "Login_app/index.html")
I want to authenticate before redirection of page
Related
I want to show user validation error but seems that this is not working in my login form here is the code
my forms.py
class LoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput())
password = forms.CharField(widget=forms.PasswordInput())
remember_me = forms.BooleanField(required=False, label='Remember Me',help_text='Keep me logged in.',widget=forms.CheckboxInput())
def clean(self, *args, **kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if username and password:
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError("This user doesn't exist")
if not user.check_password(password):
raise forms.ValidationError("Incorrect Password")
if not user.is_active:
raise forms.ValidationError("User no longer Active")
return super(LoginForm,self).clean(*args,**kwargs)
my views.py for login
def my_login(request):
if 'next' in request.GET:
messages.add_message(request, messages.WARNING, 'To Continue, Please login here!')
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
remember_me = form.cleaned_data['remember_me']
user = authenticate(username=username, password=password)
if user:
login(request, user)
if not remember_me:
request.session.set_expiry(0)
return redirect('accounts:home')
else:
request.session.set_expiry(1209600)
return redirect('accounts:home')
else:
messages.info(request, 'Please check your credentials.')
return redirect('accounts:login')
else:
form = LoginForm()
return render(request, "login.html", {'form': form})
i know i am redirecting the form if form credential is wrong but if i don't i will throw error didn't return a httpresponse it return none instead also want to what is the best way to redirect or show exact validation error of which credential is wrong
i don't want user have to see this message without any error i load page this come automatically here is my views.py
def my_login(request):
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('accounts:home')
else:
return HttpResponse('<h1>Page was found</h1>')
else:
return render(request, "login.html", {'form': form})
my forms.py
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
def clean(self, *args, **kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if username and password:
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError("User does not exist.")
if not user.is_active:
raise forms.ValidationError("User is no longer active.")
return super(LoginForm, self).clean(*args, **kwargs)
You need to submit your form only when you receive a POST request.
def my_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
# process form here
else:
form = LoginForm()
# send form to template
You will find more info about this in the documentation.
The view accounts.views.my_login_view didn't return an HttpResponse object. It returned None instead.
here is the code
def my_login_view(request):
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('/Skolar/')
else:
return HttpResponse('<h1>Page was found</h1>')
else:
return render(request, "login.html", {'form': form})
If the form is not valid there is not response so do the following :
def my_login_view(request):
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('/Skolar/')
return HttpResponse('<h1>Page was found</h1>')
return render(request, "login.html", {'form': form})
return render(request, "login.html", {'form': form})
I want to login my user after registration, but when call login(request, user) then request.user is still AnonymousUser.
def register(request):
if request.method=='POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
pwd = form.cleaned_data['password1']
user = authenticate(username=username, password=pwd)
if user is not None and user.is_active:
auth_views.login(request, user)
return redirect('/')
else:
form = RegistrationForm()
return render(request, 'registration.html', {'form' : form})
When calling login in my own login method, it works correct. But in
`register` view not:
def login(request):
if request.method=="POST":
form = AuthenticationForm(data=request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
auth_views.login(request, user)
return redirect(reverse('chat'))
else:
return redirect('/')
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form':form})
Try:
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
# Redirect to a success page.
else:
# Return a 'disabled account' error message
...
else:
# Return an 'invalid login' error message.
...
And check your session settings
Did you remember to define the Auth user in your settings file? If not, you should add the following line to your settings.py:
AUTH_USER_MODEL = 'your_app.your_usermodel'
I have a login view which looks like:
class LoginView(TemplateView):
template_name = 'login.html'
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user:
login(request, user)
return redirect(reverse('index'))
else:
messages.add_message(request, messages.ERROR, 'Login failed')
return render(request, self.template_name, {'username' : username})
Now, I'd like to modify it so if a user is alredy logged in and visits this url, template isn't rendered and insted he is redirected to the index page (or any other than the login one). I've tried overriding get method but it didn't work. What's the proper solution then?
def post(self, request):
if request.user.is_authenticated():
return HttpResponseRedirect("/yourIndex/")
else:
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user:
login(request, user)
return redirect(reverse('index'))
else:
messages.add_message(request, messages.ERROR, 'Login failed')
return render(request, self.template_name, {'username' : username})