While logged in, and navigating to home asks user to log in again

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')

What does your home.urls file look like?

Note: In the general case, your home page would not be your login page. Your login page would reside at a different url, such as login/.

You then protect your home page with the @login_required decorator to redirect the user to the login page if they go to the home page without already being logged in.

home urls.py -

from django.urls import path

from . import views

urlpatterns = [
    path('', views.home_index, name='home_index'),
    path('register/', views.register_user, name='register'),
    path('logout/', views.logout_user, name='logout'),
    path('password_reset', views.password_reset_request, name='password_reset'),
]

Reason being is that this is for internal office use so home page doesnt really need any information. I suppose I could make a simple home page that doesnt contain login form.


If I understand correctly, make my dashboard reside at ’ ’ but add a view decorator of login_required so when someone goes to 127… or domain it will redirect to login page instead of displaying the dashboard? I may have to work on implementing that as an update in the future. I dont want to break what Ive been working on. Im not super experienced.

If the dashboard is the intended “home” page, sure.

Whenever anyone tries to access any page protected by the login_required decorator and are not logged in, they will be redirected to the login page.

If you want the dashboard url protected, you also need to use the login_required decorator for it as well.

But what you’re working on isn’t working and isn’t right. After all, that’s why you’re here asking the question.

That’s very true.

I’ll work on adjusting dashboard to be the home page

I think I got it corrected so the dashboard is the main / home page and then the login is presented if the user is not auth’d.

project 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('user/', include('home.urls')),
    path('', include('dashboard.urls')),
]

home urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('login/', views.home_index, name='home_index'),
    path('register/', views.register_user, name='register'),
    path('logout/', views.logout_user, name='logout'),
    path('password_reset', views.password_reset_request, name='password_reset'),
]

home views.py

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')

dashboard views.py

@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_index')
    else:
        return render(request, 'dashboard/dashboard_index.html')

Please let me know if I missed something you mentioned.
Again. Thank you so much for helping me solve issues and guiding me in the correct way of building a django website.