Shawn
Shawn

Reputation: 163

Django: Getting 404 Error After Adding Views, Models and URLs Correctly

I am a beginner in Django. Right now, I am doing a simple app, called GameReview. It will allow the users to add the reviews of their favorite games. Right now, I am facing a 404 error. It looks like this:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/gamereview/
Using the URLconf defined in gamerevs.urls, Django tried these URL patterns, in this order:

admin/
[name='hw']
gamereview [name='gamelist']
The current path, gamereview/, didn't match any of these.

Here are my codes of models.py inside gamereview folder:

from django.db import models
from django.template.defaultfilters import slugify

# Create your models here.
class Tag(models.Model):
    label = models.CharField(max_length=20)

    def __str__(self):
        return self.label

class Game(models.Model):
    title = models.CharField(max_length=100)
    developer = models.CharField(max_length=100)
    platform = models.CharField(max_length=50, default='null')
    label_tag = models.ManyToManyField(Tag)
    slug = models.SlugField(max_length=150, default='null')

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super().save(*args, **kwargs)

class Review(models.Model):
    game = models.ForeignKey(Game, on_delete=models.CASCADE)
    review = models.CharField(max_length=1000)
    date = models.DateField(auto_now=True)
    slug = models.SlugField(max_length=150, default='null')

    def __str__(self):
        return self.review

    def save(self):
        super(Review, self).save()
        self.slug = '%i-%s' % (
            self.id, slugify(self.game.title)
        )
        super(Review, self).save()

Here are my codes of urls.py inside gamereview folder:

from . import views
from django.urls import path

urlpatterns = [
    path('gamereview', views.gamelist, name='gamelist'),
]

Here are my codes of views.py inside gamereview folder:

from django.shortcuts import render

def gamelist(request):
    context_dict = {'via': "Using template"}
    return render(request, 'gamereview/gamelist.html', context_dict)

Here are the codes of settings.py in gamerevs folder:

"""
Django settings for gamerevs project.

Generated by 'django-admin startproject' using Django 2.2.7.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'su9+iji4y-5+ddebbavou+166_p2ph1n2cls3a^x_n9o6yl1nq'

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'gamereview.apps.GamereviewConfig',
    '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 = 'gamerevs.urls'
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['/gamerevs/', TEMPLATE_PATH],
        '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 = 'gamerevs.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/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/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    STATIC_PATH,
]

Here are my codes of urls.py under gamerevs folder:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('helloworld.urls')),
    path('', include('gamereview.urls')),

]

Here are my codes of gamelist.html located inside gamereview folder of the templates folder.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Gamelist</title>
</head>
<body>
    <h1>This is Game List Page</h1>
    <strong>{{ via }}</strong><br />
    <img src="{% static "images/Super_Mario_Odyssey.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
</body>
</html>

I thought that logging into Django admin and adding new games and reviews from there would fix the issue. However, after doing it, I am still getting the 404 error.

Upvotes: 0

Views: 226

Answers (3)

Habeeb
Habeeb

Reputation: 15

Change urls.py file's (inside gamreview folder) content by;

urlpatterns = [
    path('', views.gamelist, name='gamelist'),
]

and change urls.py file's (inside project directory) content to following;

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('helloworld.urls')),
    path('gamereview/', include('gamereview.urls')),

]

Upvotes: 0

Faisal Manzer
Faisal Manzer

Reputation: 2129

urlpatterns = [
    path('gamereview', views.gamelist, name='gamelist'),
]

The URL path without trailing / (slash) will give 404 for URL ending with trailing slash.

  1. gamereview will match only gamereview
  2. gamereview/ will match gamereview/ and will redirect gamereview to gamereview/ matching both the types of URLs.

I recommend trailling slash in every URL path (in Django).

Upvotes: 2

Mukul Kumar
Mukul Kumar

Reputation: 2103

# You need to add your app name in your settings.py file 'INSTALLED_APPS'

INSTALLED_APPS = [
    'gamereview.apps.GamereviewConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'gamereview',
]

Upvotes: 0

Related Questions