Getting 404 page error when going to other .html pages

Been suck on this problem for multiple days now. My main page loads fine, but then when i click a button that’s supposed to take me to index.html i get the error posted below. When running this locally it works fine, but when deploying onto AWS (EC2, using nginx and gunicorn) its not working and giving me the error below. I’m new to using Django and AWS, any feedback is appreciated.

Error:

Request Method:    GET
Request URL:    http://IP/index.html
Using the URLconf defined in LectureLingo.urls, Django tried these URL patterns, in this order:

[name='index']
admin/
The current path, index.html, didn’t match any of these.

You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

views.py code

from django.shortcuts import render

def home(request):
    return render(request, 'home.html')

def index(request):
    return render(request, 'index.html')

Main urls.py code

from django.conf.urls import include
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('', include('transcript.urls')),
    path('index/', include('transcript.urls')),
    path('admin/', admin.site.urls),
]

urls.py inside of transcript:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index_view, name='home'),
    path('index/', views.index_view, name='index'),
]

Html homepage code

{% load static %}<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'homestyles.css' %}">
    <title>Home Page</title>
</head>
<body>
    <div class="text">LectureLingo</div>
    <div class="container">
        <div class="dropdown-container">
            <div class="dropdown-label">
                <div class="label">Translate from:</div>
                <select class="dropdown" id="dropdown1" required>
                            <option value="" disabled selected hidden>Select...</option>
                            <option value="cs">Czech</option>
                </select>
            </div>
        <div class="dropdown-label">
                <div class="label">Translate To:</div>
                <select class="dropdown" id="dropdown2" required>
                        <option value="" disabled selected hidden>Select...</option>
                        <option value="af">Afrikaans</option>
                    </select>
        </div>
    </div>
        <button id="sendButton" onclick="checkDropdowns()">Start</button>
</div>
<script src="{% static 'homeJS.js' %}"></script>
</body>
</html>

Main Javascript (only button):

document.querySelector('#sendButton').onclick = function() {
        // Check if both dropdowns have selections
        var dropdownFrom = document.getElementById('dropdown1').value;
        var dropdownTo = document.getElementById('dropdown2').value;

        if (dropdownFrom !== "" && dropdownTo !== "") {
            // Send data through WebSocket
            websocket.send(JSON.stringify({
                'dropdown1': dropdownFrom,
                'dropdown2': dropdownTo
            }));
            localStorage.setItem('detectedLanguage', dropdownTo);
            window.location.href = 'index.html';
        } else {
            alert('Please select options from both dropdowns.');
        }
    };

django.conf:

server {
    listen 80;
    server_name My IP;

    # Define the location for static files
    location /static/ {
        alias /home/ubuntu/LectureLingo/staticfiles/;
    }

    # Define how to pass Django requests
    location / {
        include proxy_params;
        proxy_pass http://unix:/home/ubuntu/LectureLingo/app.sock;
    }
}

Installed apps (from settings.py):

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = my key

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'channels',
    'transcript',
    'LectureLingo',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'LectureLingo.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "transcript/templates/")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'LectureLingo.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = '/static/'

STATIC_ROOT = '/home/ubuntu/LectureLingo/staticfiles/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

ASGI_APPLICATION = 'LectureLingo.asgi.application'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'ERROR',
            'class': 'logging.FileHandler',
            'filename': '/home/ubuntu/LectureLingo/logs/django_errors.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'ERROR',
            'propagate': True,
        },
    },
}

My directory layout:
LectureLingo/
├── LectureLingo/
│–├── settings.py
│–├── asgi.py
│–├── wsgi.py
│–└── urls.py
├── transcript/
│–├── tests.py
│–├── apps.py
│–├── views.py
│–└── templates/
│----├── home.html
│----└── index.html
│–└── urls.py
├──static/
–├── homestyles.css
–└── homeJS.js
–└── indexJS.js
–└── indexstyles.js
└── staticfiles/
–└── admin
----└── css
--------└── more files
----└──js
--------└── more files
----└── fonts
--------└── more files

The error message is rather straight forward.

You do not have a url defined for “index”. You do have one defined for “index/”. (But that’s not showing up in this list, which is an indication of a different issue.)

Please show the INSTALLED_APPS section of your settings file.

Also, please be more specific and identify the complete file and directory names for the two urls.py files you’ve posted here.

Thank you for the feedback, i’ve updated it to include my full settings.py file as well as my directory layout

From your diagram here, it appears you have the urls.py file in the templates directory, not in your transcript directory. If that’s the case, then you have it in the wrong place.

I’m actually surprised this is working at all. You have “templates” in your INSTALLED_APPS, but you don’t show a templates app.

And, in your TEMPLATES setting, you have APP_DIRS true, which means you do not need to include transcript/templates in your DIRS parameter.

(You also have your STATIC_ROOT pointing to a directory in your project, which I never recommend. Yes, it can work that way, but it’s really not the best idea.)

Sorry about that, i messed when pasting my diagram from another application, urls.py is not in templates and is inside of the transcript directory. I’ve updated the diagram to reflect this.

Your right, having templates in the INSTALLED_APPS doesn’t make sense. I was honestly just guessing and testing while trying to debug this issue so i just threw it in there. The same applies for having transcript/templates in TEMPLATES. I was honestly throwing all of my knowledge at the wall and seeing what stuck.

Your right, I read online that it isn’t good practice to have the static folder in root, but i didn’t really care to change it since this is my introductory to django and this is just a pet project, thank you though

So with all these corrections made (including the urls you’re using), has the issue been resolved?

No, Unfortunately not

ive updated it once again to show what my root urls.py looks like now, maybe i misunderstood when you said that i didnt have a url defined for index?

You do not have a url defined for index.html. You have a url defined for index/. They are not the same.

Side note: Please do not continue to edit your original post, that makes this too hard to follow. If you need to post a correction or update, post the revised code or messages in a new reply.

Im extremely new to Django, your probably going to have to spell it out for me, because im honestly pretty confused.

From my understanding, my Django urls.py configuration within the transcript app correctly maps the URL path index/ to the index view, which in turn is set up to render index.html. My javascript correctly redirects to the index/ path.

My apologies for constantly updating the original post, i didnt know it was better practice to update the changes in a reply.

My current set-up looks like this

root urls.py:

urlpatterns = [
    path('', include('transcript.urls')),
    path('index/', include('transcript.urls')),
    path('admin/', admin.site.urls),
]

views.py:

from django.shortcuts import render

def home(request):
    return render(request, 'home.html')

def index(request):
    return render(request, 'index.html')

urls.py inside of transcript:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),  # Assuming you have a home view for the root URL
    path('index/', views.index, name='index'),  # Add this line if not already present
]

The javascript line that redirects to index.html:

window.location.href = 'index/';

A browser issues a request to a url. (It doesn’t matter if it’s the address bar or JavaScript.)

The web server receives the request and passes it to Django.

Django takes the url being requested, and searches for it in the various url patterns that have been defined.

When it finds a match, it calls the corresponding view.

That view returns a response. What that view does to create the response is not relevent to this sequence of events.

So, the browser must issue the request for a defined url.

You do not have index.html defined as a url. You cannot make a valid request to a url “index.html”.

With the various corrections and updates that you have made, please post (new reply, do not edit the original) the error being generated. Also, instead of posting the image from the browser, post the complete error message from the server console.

Sorry for the late response, life got in the way.

So from my understanding, when the button is pressed on the home page, it goes into javascript and gets the url.

document.querySelector('#sendButton').onclick = function() {
        // Check if both dropdowns have selections
        var dropdownFrom = document.getElementById('dropdown1').value;
        var dropdownTo = document.getElementById('dropdown2').value;

        if (dropdownFrom !== "" && dropdownTo !== "") {
            // Send data through WebSocket
            websocket.send(JSON.stringify({
                'dropdown1': dropdownFrom,
                'dropdown2': dropdownTo
            }));
            localStorage.setItem('detectedLanguage', dropdownTo);
            window.location.href = 'index/';
        } else {
            alert('Please select options from both dropdowns.');
        }
    };

The line window.location.href = 'index/'; is what returns index/

index/ is then passed to django and django takes the url (index/) and searches for it in urls.py

urls.py inside of the transcript folder:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),  # Assuming you have a home view for the root URL
    path('index/', views.index, name='index'),  # Add this line if not already present
]

main urls.py:

from django.conf.urls import include
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('', include('transcript.urls')),
    path('index/', include('transcript.urls')),
    path('admin/', admin.site.urls),
]

Once a match is found, it calls view.py:

from django.shortcuts import render

def home(request):
    return render(request, 'home.html')

def index(request):
    return render(request, 'index.html')

It seems like all the pieces are there to get to the url http://IP/index/
Yet this error is still being given:

Page not found (404)
Request Method:	GET
Request URL:	http://IP/index/
Using the URLconf defined in LectureLingo.urls, Django tried these URL patterns, in this order:

[name='index']
admin/
The current path, index/, didn’t match any of these.

You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

console in web browser :

Error with Permissions-Policy header: Origin trial controlled feature not enabled: 'attribution-reporting'.
Error with Permissions-Policy header: Origin trial controlled feature not enabled: 'run-ad-auction'.
Error with Permissions-Policy header: Origin trial controlled feature not enabled: 'join-ad-interest-group'.
Error with Permissions-Policy header: Origin trial controlled feature not enabled: 'browsing-topics'.
 
GET http://IP/index/ 404 (Not Found)
document.querySelector.onclick @ static/homeJS.js:25

The Cross-Origin-Opener-Policy header has been ignored, index/:1 because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can also use the 'localhost' origin instead. See https://www.w3.org/TR/powerful-features/#potentially-trustworthy-origin and https://html.spec.whatwg.org/#the-cross-origin-opener-policy-header.

Im guessing im not understanding something correctly

Hey man, i appreciate your all your help, turns out my web browser was caching my files. and was not reflecting the updates i was making since the first time. preforming ctr + f5 on chrome and edge ended up fixing the issue.

Thanks again for your help!