Redirect to the main page if authenticated - django

I got some problems with redirecting.
When I already logged in, and try go to "/accounts/login", it still goes to this link, and if I change in url.py path for example "accounts/logins", the redirect is working, but if not authenticated it says me that:
UnboundLocalError: local variable 'context' referenced before assignment
AND "/accounts/login" is still available if I remove it in url.py
views.py
def loginPage(request):
if request.user.is_authenticated:
return redirect("index")
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('index')
else:
messages.info(request, 'Username OR password is incorrect')
context = {}
return render(request, 'registration/login.html', context)
url.py
urlpatterns = [
path('login/', views.loginPage, name='loginPage'),
path('logout/', views.logoutUser, name='logoutUser'),
path('register/', views.registerPage, name='registerPage'),
]

In order to redirect to an specific url once logged in you can set in your settings.py the following:
LOGIN_REDIRECT_URL = '/'
hope this is what are you looking for

Try this code...
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('index')
else:
messages.info(request, 'Username OR password is incorrect')
return redirect('/login/')
else:
if request.user.is_authenticated:
return redirect('/index/')
else:
context = {}
return render(request, 'registration/login.html',context)

Related

How can i ensure that users can be logged in and after logging out, they can still log in again

def LoginForm(request):
Form= 'Login'
if request.user.is_authenticated:
return redirect('home')
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
# to see if the user exist within the db
try:
user = User.objects.get(username=username)
except:
messages.error(request, 'User does not exist')
# if the user exist, we will use the auth method, import it
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.error(request, 'Username or password does not exist')
context = {'Form': Form}
return render(request, 'base/registration_log.html', context)
The above code is the user log in function. but once they log in and log out, they are not able to log in again

Django Login Authentication: I am able to SignUp new user and create new user as well but UNABLE to login as SignUp user

I'm able to SignUp new user as well but UNABLE to login for handlelogin
def handlelogin(request):
if request.method == 'POST':
loginemail= request.POST['loginemail']
loginpass = request.POST['loginpass']
user = authenticate(request, username=loginemail, password=loginpass)
if user is not None:
print(loginemail, loginpass)
login(request, user)
messages.success(request, "Successfullly Logged-In")
return redirect('/')
else:
messages.error(request, "Invalid Credentials, Please Try Again")
return redirect('/')
return HttpResponse('404 - Page Not Find')
I have tried print() statement to check and it do work in else statement only, not in if user is not none.
NOTE: THE SYNTAX IN QUESTION IS LITTLE BIT DISTURBED... BUT IN CODE IT IS COMPLTELY FINE.
BTW I use Django forms for login and logout users:
views.py:
def user_login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(request, username=cd['username'], password=cd['password'])
if user is not None:
login(request, user)
messages.success(request, 'you logged in successfully', 'success')
return HttpResponseRedirect('dashboard/')
else:
messages.error(request, 'username or password is wrong', 'danger')
else:
form = UserLoginForm()
return render(request, 'login.html', {'form': form})
def user_logout(request):
logout(request)
messages.success(request, 'you logged out successfully', 'success')
return HttpResponseRedirect('')
forms.py
class UserLoginForm(forms.Form):
username = forms.CharField(max_length=30)
password = forms.CharField(max_length=50)
urls.py
urlpatterns = [
path('', user_login),
path('logout/', user_logout, name='user_logout'),
]
Also if you haven't make sign Up page you should make user manually by python3 manage.py createsuperuser command.
For sign Up page:
urls.py
urlpatterns = [
...
path('signup/', signup, name='signup'),
]
views.py
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
forms.py
class SignUpForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

Autheticate before redirecting to dashboard

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

django customizing user view?

i make customizing user.
so i need to login with email.
user = authenticate(email=email, password=password) seems not working...
help me...
let me know of how to fix my views.py.
here is my view.
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.core.urlresolvers import reverse
from django.shortcuts import render
from LanguageExchange.forms import UserCreationForm,UserChangeForm
def index(request):
context_dict = {'boldmessage': "Crunchy, creamy, cookie, candy, cupcake!"}
return render(request, 'LanguageExchange/index.html', context=context_dict)
def register(request):
# A boolean value for telling the template
# whether the registration was successful.
# Set to False initially. Code changes value to
# True when registration succeeds.
registered = False
if request.method == 'POST':
user_form = UserCreationForm(data=request.POST)
# change_form = UserChangeForm(data=request.POST)
# if the two forms are valid..
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
#if change_form.is_valid():
# change = change_form.save()
# change.set_password(user.password)
# change.user = user
registered = True
else:
print(user_form.errors)
else:
user_form = UserCreationForm()
# change_form = UserChangeForm()
return render(request,
'LanguageExchange/register.html',
{'user_form': UserCreationForm,
'registered': registered})
def user_login(request):
if request.method == 'POST':
username = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(email=email, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Your Rango account is disabled.")
else:
print("Invalid login details: {0}, {1}".format(email, password))
return HttpResponse("Invalid login details supplied.")
else:
return render(request, 'LanguageExchange/login.html', {})
let me know of how to fix my views.py.
delete
user.set_password(user.password)
in register;
change
user = authenticate(email=email, password=password)
to
user = authenticate(username=email, password=password)
in user_login.

django.contrib.auth.views.login returns Anonymous user

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'