Python Django Authentication (Login/Register) Errors

163 Views Asked by At

I am making a weather application and wanted to incorporate authentication into it, so I decided to use django and postgres as my backend. I am new to all of this, so this may seem like a really dumb and easy fix for some of you... but for me I've spent a few hours with no success.

The error I come through is:

I have 3 html pages, dashboard.html, login.html and register.html.

My folder structure is as follows:

--- Folder Structure ---
.DS_Store
README.md
db.sqlite3
manage.py
[my_weather_project]
    ├── __init__.py
    ├── [__pycache__]
        ├── __init__.cpython-310.pyc
        ├── settings.cpython-310.pyc
        ├── urls.cpython-310.pyc
        └── wsgi.cpython-310.pyc
    ├── asgi.py
    ├── settings.py
    ├── [staticfiles] # a lot of files here that I did not include
    ├── urls.py
    └── wsgi.py
my_weather_project.zip
[myapp]
    ├── .DS_Store
    ├── __init__.py
    ├── [__pycache__]
        ├── __init__.cpython-310.pyc
        ├── admin.cpython-310.pyc
        ├── apps.cpython-310.pyc
        ├── forms.cpython-310.pyc
        ├── models.cpython-310.pyc
        ├── urls.cpython-310.pyc
        └── views.cpython-310.pyc
    ├── admin.py
    ├── apps.py
    ├── forms.py
    ├── [migrations]
        ├── 0001_initial.py
        ├── __init__.py
        └── [__pycache__]
            ├── 0001_initial.cpython-310.pyc
            └── __init__.cpython-310.pyc
    ├── models.py
    ├── [templates]
        ├── .DS_Store
        ├── [dashboard]
            └── dashboard.html
        └── [registration]
            ├── login.html
            └── register.html
    ├── tests.py
    ├── urls.py
    └── views.py
requirements.txt
[static]
    └── [js]
        └── cookies.js
Here is my cookies.js: 

document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('registration-form');  // Replace with your form's ID
    form.addEventListener('submit', function (event) {
        event.preventDefault();

        const formData = new FormData(form);

        fetch('dashboard/dashboard.html', {  // Use the correct AJAX endpoint from your urls.py
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
            }
        })
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error('Network response was not ok');
            }
        })
        .then(data => {
            console.log('Success:', data);
            // Update your HTML with the data if needed
        })
        .catch(error => {
            console.error('Error:', error);
        });
    });
});

Here is my views.py:

from django.contrib.auth import login, logout, authenticate
from django.shortcuts import render, redirect
from .forms import RegistrationForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            print(request, user) # debugging
            return redirect('myapp:dashboard')
    else:
        form = UserCreationForm()
    return render(request, 'registration/register.html', {'form': form})

def user_login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('myapp:dashboard')
    return render(request, 'myapp/templates/registration/login.html')

def user_logout(request):
    logout(request)
    return redirect('login')

@login_required
def dashboard(request):
    return render(request, 'myapp:dashboard')

def home(request):
    return render(request, 'myapp:dashboard')

Here is my urls.py:

from django.urls import path
from . import views

app_name = 'myapp'

urlpatterns = [
    path('register/', views.register, name='register'),  # Check this URL
    path('login/', views.user_login, name='login'),
    path('logout/', views.user_logout, name='logout'),
    path('dashboard/', views.dashboard, name='dashboard'),
    path('', views.dashboard, name='home'),
]

here is my_weather_project/urls.py: 

from django.contrib import admin
from django.urls import path, include
from myapp import views  # Import your views


urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.dashboard, name='home'), 
    path('accounts/', include('django.contrib.auth.urls')), 
    path('myapp/', include('myapp.urls')), 
]

here is my_weather_project/settings.py:


from pathlib import Path

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


# Quick-start development settings - unsuitable for production

# SECURITY WARNING: keep the secret key used in production secret!
import secrets

SECRET_KEY = secrets.token_urlsafe(50)

X_FRAME_OPTIONS = 'DENY'
SESSION_COOKIE_SECURE = True
SESSION_ENGINE = 'django.contrib.sessions.backends.db'


DEBUG = True

ALLOWED_HOSTS = ['*']

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
)


INSTALLED_APPS = [
    'myapp',
    '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 = 'my_weather_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'my_weather_project.wsgi.application'


# Database

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'weatherappdb', 
        'USER': 'postgres',  
        'PASSWORD': '**********',  
        'HOST': 'localhost', 
        'PORT': '',  
    }
}

LOGIN_REDIRECT_URL = '/dashboard'  

# Password validation

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

TIME_ZONE = 'GMT'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
CSRF_COOKIE_SECURE = False  # Set to True for production with HTTPS

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

import os
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR / "static",
]
STATIC_ROOT = BASE_DIR / "staticfiles"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Here is my models.py:

from django.db import models
from django.contrib.auth.models import User

class Location(models.Model):
    name = models.CharField(max_length=100)
    latitude = models.FloatField()
    longitude = models.FloatField()

class WeatherData(models.Model):
    location = models.ForeignKey(Location, on_delete=models.CASCADE)
    timestamp = models.DateTimeField()
    temperature = models.DecimalField(max_digits=5, decimal_places=2)
    humidity = models.DecimalField(max_digits=5, decimal_places=2)

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

The problem I am getting is as follows:

when i do python3 manage.py runserver in my_weather_project folder on my terminal, it loads fine and I run it on the server: http://127.0.0.1:8000/. Then, as it loads on the login.html, i press on don't have an account and it loads on the register.html, fine. The problem occurs when I click on the register button after entering username and password, and nothing happens but on the terminal I get this:

alby@Albertos-iMac my_weather_project $ python3 manage.py runserver
Watching for file changes with StatReloader Performing system checks...

System check identified no issues (0 silenced). November 03, 2023 - 21:09:17 Django version 4.2.7, using settings 'my_weather_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.

[03/Nov/2023 21:09:20] "GET / HTTP/1.1" 302 0
[03/Nov/2023 21:09:20] "GET /accounts/login/?next=/ HTTP/1.1" 200 962
[03/Nov/2023 21:09:20] "GET /static/js/cookies.js HTTP/1.1" 304 0
[03/Nov/2023 21:09:22] "GET /myapp/register/ HTTP/1.1" 200 1695
Not Found: /myapp/register/dashboard/dashboard.html
[03/Nov/2023 21:09:26] "POST /myapp/register/dashboard/dashboard.html HTTP/1.1" 404 3303
Not Found: /myapp/register/dashboard/dashboard.html
[03/Nov/2023 21:09:27] "POST /myapp/register/dashboard/dashboard.html HTTP/1.1" 404 3303
[03/Nov/2023 21:09:37] "GET /accounts/login/ HTTP/1.1" 200 962
[03/Nov/2023 21:09:40,276] - Broken pipe from ('127.0.0.1', 59430)
[03/Nov/2023 21:09:40] "POST /accounts/login/ HTTP/1.1" 302 0
Not Found: /dashboard
[03/Nov/2023 21:09:40] "GET /dashboard HTTP/1.1" 404 2444

furthermore, I also get this ^^ as you can see when I go to login and even a different error shows but I don't know what, but they are both linked to dashboard.html.

I have no clue what the problem is, I have spent hours on this and I have asked everyone and have even asked chatpgt at some point, though as you know it failed to provide me a corrrect solution.

Here is also my github repo: https://github.com/albystack/cscoursework Please can someone guide me on how to fix this error, thanks.

I tried everything, and what I expected was after the register button it showed the dashboard.html page.

1

There are 1 best solutions below

0
On

Seems like the dashboard template cannot be found

Not Found: /myapp/register/dashboard/dashboard.html

The reason probably is that the dashboard() view doesn't render any template. You probably want sth like this:

def dashboard():
    # ...
    return render(request, 'myapp/templates/dashboard/dashboard.html', {})