I have a home app that displays a login page at 127.0.0.1:800/, if I am currently logged in and go to the above address it will ask me to login again. Obviously, this can be annoying to the end user. I would like for a check to be in place so if the user is already logged in it will take them straight to the dashboard at 127.0.0.1:8000/dashboard
In my main project titled “main” I currently have 2 applications; home and dashboard
home views.py -
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
# Password Reset
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse
from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.models import User
from django.template.loader import render_to_string
from django.db.models.query_utils import Q
from django.utils.http import urlsafe_base64_encode
from django.contrib.auth.tokens import default_token_generator
from django.utils.encoding import force_bytes
# Create your views here.
from .forms import RegisterForm
def home_index(request):
if request.method == 'POST':
username = request.POST['username'].lower()
password = request.POST['password']
# Authenticate
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# messages.success(request, "Login Successful.")
return redirect('dashboard_index')
else:
messages.error(request, "Login Required to view. Please login in.")
return redirect('home_index')
else:
return render(request, 'home/index.html')
def logout_user(request):
logout(request)
messages.success(request, "You have been successfully logged out.")
return redirect('home_index')
def register_user(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
# Auth and Login
username = form.cleaned_data['username'].lower()
password = form.cleaned_data['password1']
user = authenticate(username=username.lower(), password=password)
login(request, user)
return redirect('dashboard_index')
else:
form = RegisterForm()
return render(request, 'home/register.html', {'form':form})
return render(request, 'home/register.html', {'form':form})
def password_reset_request(request):
if request.method == "POST":
password_reset_form = PasswordResetForm(request.POST)
if password_reset_form.is_valid():
data = password_reset_form.cleaned_data['email'].lower()
associated_users = User.objects.filter(Q(email=data))
if associated_users.exists():
for user in associated_users:
subject = "Password Reset Request | Tracker"
email_template_name = "password/password_reset_email.txt"
c = {
'email':user.email,
'domain':'127.0.0.1:8000',
'site_name':'Tracker',
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'user': user,
'token': default_token_generator.make_token(user),
'protocol':'http',
}
email = render_to_string(email_template_name, c)
try:
send_mail(subject, email, 'admin@admin.com', [user.email], fail_silently=False)
except BadHeaderError:
return HttpResponse("Invaild header found.")
messages.success(request, f'An email with password reset instructions as been sent to your inbox at {data}.')
return redirect('/password_reset/done/')
messages.success(request, f'An email with password reset instructions as been sent to your inbox at {data}.')
password_reset_form = PasswordResetForm()
return render(request=request, template_name='password/password_reset.html', context={'password_reset_form':password_reset_form})
main urls.py -
from django.contrib import admin
from django.urls import path, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls),
# path('accounts/', include('django.contrib.auth.urls')),
path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='password/password_reset_done.html'), name='password_reset_done'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password/password_reset_confirm.html"), name='password_reset_confirm'),
path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='password/password_reset_complete.html'), name='password_reset_complete'),
path('', include('home.urls')),
path('dashboard/', include('dashboard.urls')),
]
dashboard views.py -
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.decorators import login_required
# Create your views here.
login_success = "Login Successful."
login_error = "Login Unsuccessful. Try again or contact site administrator."
@login_required
def dashboard_index(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
# Authenticate
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
messages.success(request, login_success)
return redirect('dashboard_index')
else:
messages.error(request, login_error)
return redirect('home')
else:
return render(request, 'dashboard/dashboard_index.html')