URL evaluates to 'slug' literally instead of the variable slug

143 views
Skip to first unread message

Michael Starr

unread,
Nov 30, 2022, 8:52:36 AM11/30/22
to Django users
Code is first, query is last (below). Thanks in advance.


home directory urls.py
from django.contrib import admin
from django.urls import path,include
from . import views

urlpatterns = [
    path("admin/", admin.site.urls, name='admin'),
    path("", views.Home.as_view(), name="home"),
    path("pet/", include('pet.urls')),
]



home directory views.py
from django.shortcuts import render
from django.views.generic.detail import DetailView
from django.views.generic.base import TemplateView
from django.views.generic import View

class Home(TemplateView):
    template_name = 'home.html'



app "pet" urls.py
from django.contrib import admin
from django.urls import path
from . import views as pet_views
from .models import Pet


urlpatterns = [
    path('<slug:slug>', pet_views.PetDetailView.as_view(), name='pet_details'),]



app "pet" views.py
from django.shortcuts import render
from django.views.generic.detail import DetailView
from pet.models import Pet

class PetDetailView(DetailView):
    model = Pet
    slug_url_kwarg = 'slug'
    slug_field = 'slug'





app "pet" models.py
from django.db import models
from django.utils.text import slugify

class Pet(models.Model):
    name = models.CharField(max_length=255)
    age = models.IntegerField()
    slug = models.SlugField(allow_unicode=True, max_length=100, unique=True, default="default_pet_slug")

    def __str__(self):
        return self.name

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

    def get_absolute_url(self):
        return reverse("pet:pet_details", kwargs={"slug": self.slug})




apps.py
from django.apps import AppConfig

class PetConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "pet"




admin.py
from django.contrib import admin
from .models import Pet

admin.site.register(Pet)




settings.py
"""
Django settings for pet_memorial project.

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

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

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

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
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-zfb*2fvvz=_komv(#8(ho)ckc-+a3$^!@tua2#n^c&0*st=xm6"

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "pet",
]

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 = "pet_memorial.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
                    'pet_memorial/templates/',
                    'pet/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 = "pet_memorial.wsgi.application"


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

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


# Password validation
# https://docs.djangoproject.com/en/4.1/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.1/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.1/howto/static-files/

STATIC_URL = "static/"

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

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"




home folder / home.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    test
    <a href="{% url 'pet_details' slug='slug' %}">Pet Profile: Mocha</a>
  </body>
</html>




"pet" templates folder / pet_profile.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    {{ pet_details }}
  </body>
</html>




the error
Page not found (404)
No pet found matching the query
Request Method:
  GET

Request URL:
  http://127.0.0.1:8000/pet/slug

Raised by:
  pet.views.PetDetailView

Using the URLconf defined in pet_memorial.urls, Django tried these URL patterns, in this order:

  1. admin/
  2. [name='home']
  3. pet/ <slug:slug> [name='pet_details']

The current path, pet/slug, matched the last one.

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.



-------------------------------------




I am trying to make an app for people to share information about their pets (animals). I have made the framework files so far, but have run into a problem getting the pet's slug (which should be unique for each pet, in order to have a unique URL for each pet's profile page with no collisions between pets if by chance named the same).

I have no idea why the slug is not evaluating to the default default_pet_slug in models.py as defined by default = "default_pet_slug". But in any case, why doesn't the slug match itself? It is a variable in both the url.py file (in pets app) and in the home.html a-href link. The homepage renders just fine, but this error pops up when I click on the link defined in the homepage's html template, home.html.

A PDF printout of the error page is attached for verity.

Any help is appreciated. Many thanks.

Michael

Page not found at _pet_slug.pdf

peteru mimo

unread,
Nov 30, 2022, 9:05:35 AM11/30/22
to Django users
Make your urls patterns at pet app 

path('pet<slug:slug>/', pet_views.PetDetailView.as_view(), name='pet_details'),] 

Ryan Nowakowski

unread,
Nov 30, 2022, 10:15:56 AM11/30/22
to Django users
On Tue, Nov 29, 2022 at 06:35:25PM -0800, Michael Starr wrote:
> *home folder / home.html*
> <!DOCTYPE html>
> <html lang="en" dir="ltr">
> <head>
> <meta charset="utf-8">
> <title></title>
> </head>
> <body>
> test
> <a href="{% url 'pet_details' slug='slug' %}">Pet Profile: Mocha</a>
> </body>
> </html>

In your home.html you've hard coded a link to a specific pet named Mocha.
You'll need to hard code the slug as well so:

<a href="{% url 'pet_details' slug='mocha' %}">Pet Profile: Mocha</a>

Michael Starr

unread,
Nov 30, 2022, 12:18:29 PM11/30/22
to django...@googlegroups.com
Thank you. Though, that hard codes everything, which is bad. How do I
generalize it?

Also, this worked. I had to specify template_name = pet_profile.html in
the pet detail view.

Ryan Nowakowski

unread,
Nov 30, 2022, 7:43:47 PM11/30/22
to django...@googlegroups.com
On Wed, Nov 30, 2022 at 09:16:39AM -0800, Michael Starr wrote:
> Thank you. Though, that hard codes everything, which is bad. How do I
> generalize it?

You'll need to do 2 things:

1. Add the pet(s) you want to the template context, probably by implementing get_context_data[1].

2. Change your template to use the pet from the template context instead of the hard code pet, Mocha. Assuming your pet in the template context is named 'pet':

<a href="{% url 'pet_details' slug=pet.slug %}">Pet Profile: {{ pet.name }}</a>

...alternatively since you've implemented get_absolute_url:

<a href="{{ pet.get_absolute_url }}">Pet Profile: {{ pet.name }}</a>


[1] https://docs.djangoproject.com/en/4.1/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin.get_context_data

Michael Starr

unread,
Dec 4, 2022, 4:02:27 PM12/4/22
to Django users
Thank you. I will check this out. Sorry for the slow reply.

Michael Starr

unread,
Dec 4, 2022, 4:03:25 PM12/4/22
to Django users
Thank you, Peter. I forgot to acknowledge your contribution.

On Wednesday, November 30, 2022 at 4:43:47 PM UTC-8 Ryan Nowakowski wrote:

ELVIS MAKASI

unread,
Dec 5, 2022, 9:36:30 AM12/5/22
to django...@googlegroups.com
Good !😁

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e8afb697-d067-4cc6-bda8-93dd9b8748een%40googlegroups.com.
Message has been deleted

Michael Starr

unread,
Dec 15, 2022, 5:54:59 PM12/15/22
to Django users
Sorry for that crass, asinine comment. I had a flare up of my condition.
Thank you all for the help.
Mike

On Sunday, December 11, 2022 at 4:32:04 PM UTC-8 Michael Starr wrote:
It's poorly written and mine isn't. Am I better than them.

Michael Starr

unread,
Dec 16, 2022, 8:51:14 PM12/16/22
to Django users
I hope someone is still subscribed to this post. I had another question...

I looked up your link, about context dictionary, presumably to modify the value returned by the function, like you said, to add the pets to it. I don't know what to loop or iterate over to get all the pets, first off. I know how to add them, I think, that would just be context[pet id or something] = <pet object instance>. Secondly, I'm assuming this function, get_context_data, goes in the models file. I understand how to retrieve context from the dictionary, you explained that as well as the professor in the course I took on Django, so no problems there (so far).

I think that's it, actually.

Thanks in advance, hugely appreciate any help anyone can offer.

Best,
Mike

Michael Starr

unread,
Dec 20, 2022, 4:45:10 PM12/20/22
to Django users
No reply yet, so bump.
Reply all
Reply to author
Forward
0 new messages