NoReverseMatch--Seems that Django doesn't detect the app url

232 views
Skip to first unread message

Michael Starr

unread,
Feb 25, 2023, 3:19:13 PM2/25/23
to Django users
I have a pet memorial project, and some urls in pet_memorial

pet memorial urls.py
from django.contrib import admin
from django.urls import path, include
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', views.HomeView.as_view(), name='home_view'),
    path('', include('pet_profile.urls')),
]

and some urls in the pet_profile app

pet profile app urls.py
from django.contrib import admin
from django.urls import path
from pet_profile import views

urlpatterns = [
    path("pet/<slug:slug>/", views.PetDetailView.as_view(), name = "pet_profile"),
    path("owner/<slug:slug>/", views.PetOwnerProfileView.as_view(), name = "owner_profile"),
]

As you can see, pet memorial urls has an include call which includes the pet profile urls, so theoretically it should be checking for all urls whether they are in the project or in the app.

Now, I am trying to use the owner_profile url name to create a template-tagg'd anchor url link to the pet_owner_profile.html template.

home.html
{% extends "base.html" %}
{% block header %}
   
{% endblock %}
{% block content %}
    <a href="{% url 'owner_profile' %}">test</a>
{% endblock %}

In the views file I previously had template_name set to home.html, but now it is pet_owner_profile.html. I think that makes more sense? Otherwise the link would point back to itself.

views.py
from django.shortcuts import render
from django.views.generic import (TemplateView,ListView,
                                  DetailView,CreateView,
                                  UpdateView,DeleteView)
from pet_profile.models import PetOwner, Pet, PetPhoto, PetStory

class PetOwnerListView(ListView):
    model = PetOwner
    context_object_name = "owner_list"
    template_name = "home.html"

class PetOwnerProfileView(DetailView):
    model = PetOwner
    context_object_name = "owner"
    template_name = "pet_owner_profile.html"

class PetListView(ListView):
    model = Pet
    context_object_name = "pet_list"

class PetDetailView(DetailView):
    model = Pet
    context_object_name = "pet"

class PetPhotoListView(ListView):
    model = PetPhoto
    context_object_name = "pet_photo_list"

class PetPhotoDetailView(DetailView):
    model = PetPhoto
    context_object_name = "pet_photo"

class PetStoryListView(ListView):
    model = PetStory
    context_object_name = "pet_story_list"

class PetStoryDetailView(DetailView):
    model = PetStory
    context_object_name = "pet_story"


In either case, I get a noreversematch error when trying to render the home html page that includes the url template tag with owner_profile as the template tag name. It is a valid url name so I don't understand why it doesn't detect it. I don't know quite what's going on.

error:
NoReverseMatch at /home/ Reverse for 'owner_profile' with no arguments not found. 1 pattern(s) tried: ['owner/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
Request Method:

GET

Request URL:

http://127.0.0.1:8000/home/

Django Version:

4.1.7

Exception Type:

NoReverseMatch

Exception Value:

Reverse for 'owner_profile' with no arguments not found. 1 pattern(s) tried: ['owner/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']

Exception Location:

C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix

Raised during:

pet_memorial.views.HomeView

Python Executable:

C:\Users\starr\Code\pet_memorial\.venv\Scripts\python.exe

Python Version:

3.11.2

Python Path:

['C:\\Users\\starr\\Code\\pet_memorial', 'C:\\Program Files\\Python311\\python311.zip', 'C:\\Program Files\\Python311\\DLLs', 'C:\\Program Files\\Python311\\Lib', 'C:\\Program Files\\Python311', 'C:\\Users\\starr\\Code\\pet_memorial\\.venv', 'C:\\Users\\starr\\Code\\pet_memorial\\.venv\\Lib\\site-packages']

Server time:

Sat, 25 Feb 2023 20:15:57 +0000
Error during template rendering

In template C:\Users\starr\Code\pet_memorial\pet_memorial\templates\pet_memorial\home.html, error at line 6

Reverse for 'owner_profile' with no arguments not found. 1 pattern(s) tried: ['owner/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
1

{% extends "base.html" %}

2

{% block header %}

3


4

{% endblock %}

5

{% block content %}

6

<a href="{% url 'owner_profile' %}">test</a>

7


8

{% endblock %}
Traceback Switch to copy-and-paste view
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\core\handlers\exception.py, line 56, in inner
    1. response = get_response(request)
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\core\handlers\base.py, line 220, in _get_response
    1. response = response.render()
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\response.py, line 114, in render
    1. self.content = self.rendered_content
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\response.py, line 92, in rendered_content
    1. return template.render(context, self._request)
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\backends\django.py, line 61, in render
    1. return self.template.render(context)
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\base.py, line 175, in render
    1. return self._render(context)
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\base.py, line 167, in _render
    1. return self.nodelist.render(context)
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\base.py, line 1005, in render
    1. return SafeString("".join([node.render_annotated(context) for node in self]))
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\base.py, line 1005, in <listcomp>
    1. return SafeString("".join([node.render_annotated(context) for node in self]))
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\base.py, line 966, in render_annotated
    1. return self.render(context)
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\loader_tags.py, line 157, in render
    1. return compiled_parent._render(context)
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\base.py, line 167, in _render
    1. return self.nodelist.render(context)
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\base.py, line 1005, in render
    1. return SafeString("".join([node.render_annotated(context) for node in self]))
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\base.py, line 1005, in <listcomp>
    1. return SafeString("".join([node.render_annotated(context) for node in self]))
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\base.py, line 966, in render_annotated
    1. return self.render(context)
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\loader_tags.py, line 63, in render
    1. result = block.nodelist.render(context)
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\base.py, line 1005, in render
    1. return SafeString("".join([node.render_annotated(context) for node in self]))
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\base.py, line 1005, in <listcomp>
    1. return SafeString("".join([node.render_annotated(context) for node in self]))
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\base.py, line 966, in render_annotated
    1. return self.render(context)
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\template\defaulttags.py, line 471, in render
    1. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\urls\base.py, line 88, in reverse
    1. return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
    Local vars
  • C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix
    1. raise NoReverseMatch(msg)
    Local vars
Request information USER

starr

GET

No GET data

POST

No POST data

FILES

No FILES data

COOKIES
Variable

Value

csrftoken

'vyMGMPTzLclJ6K3awA182THxQiX4RFO8'

sessionid

'79io3ywxr5hke9u5itq2pjfnlsv0rxgq'
META
Variable

Value

ALLUSERSPROFILE

'C:\\ProgramData'

APPDATA

'C:\\Users\\starr\\AppData\\Roaming'

CHOCOLATEYINSTALL

'C:\\ProgramData\\chocolatey'

CHOCOLATEYLASTPATHUPDATE

'132763030117094841'

CHROME_CRASHPAD_PIPE_NAME

'\\\\.\\pipe\\LOCAL\\crashpad_4752_NCEKIXAPVVVFXZAI'

COLORTERM

'truecolor'

COMMONPROGRAMFILES

'C:\\Program Files\\Common Files'

COMMONPROGRAMFILES(X86)

'C:\\Program Files (x86)\\Common Files'

COMMONPROGRAMW6432

'C:\\Program Files\\Common Files'

COMPUTERNAME

'DAFFY'

COMSPEC

'C:\\WINDOWS\\system32\\cmd.exe'

CONFIGSETROOT

'C:\\WINDOWS\\ConfigSetRoot'

CONTENT_LENGTH

''

CONTENT_TYPE

'text/plain'

CSRF_COOKIE

'vyMGMPTzLclJ6K3awA182THxQiX4RFO8'

DJANGO_SETTINGS_MODULE

'pet_memorial.settings'

DRIVERDATA

'C:\\Windows\\System32\\Drivers\\DriverData'

FPS_BROWSER_APP_PROFILE_STRING

'Internet Explorer'

FPS_BROWSER_USER_PROFILE_STRING

'Default'

GATEWAY_INTERFACE

'CGI/1.1'

GIT_ASKPASS

'********************'

HOMEDRIVE

'C:'

HOMEPATH

'\\Users\\starr'

HTTP_ACCEPT

'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8'

HTTP_ACCEPT_ENCODING

'gzip, deflate, br'

HTTP_ACCEPT_LANGUAGE

'en-US,en;q=0.5'

HTTP_CONNECTION

'keep-alive'

HTTP_COOKIE

('csrftoken=vyMGMPTzLclJ6K3awA182THxQiX4RFO8; ' 'sessionid=79io3ywxr5hke9u5itq2pjfnlsv0rxgq')

HTTP_HOST

'127.0.0.1:8000'

HTTP_SEC_FETCH_DEST

'document'

HTTP_SEC_FETCH_MODE

'navigate'

HTTP_SEC_FETCH_SITE

'none'

HTTP_SEC_FETCH_USER

'?1'

HTTP_SEC_GPC

'1'

HTTP_UPGRADE_INSECURE_REQUESTS

'1'

HTTP_USER_AGENT

('Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 ' 'Firefox/110.0')

LANG

'en_US.UTF-8'

LOCALAPPDATA

'C:\\Users\\starr\\AppData\\Local'

LOGONSERVER

'\\\\DAFFY'

NUMBER_OF_PROCESSORS

'12'

ONEDRIVE

'C:\\Users\\starr\\OneDrive'

ONEDRIVECONSUMER

'C:\\Users\\starr\\OneDrive'

ORIGINAL_XDG_CURRENT_DESKTOP

'undefined'

OS

'Windows_NT'

PATH

('C:\\Users\\starr\\Code\\pet_memorial\\.venv\\Scripts;C:\\Program ' 'Files\\Python311\\Scripts\\;C:\\Program Files\\Python311\\;C:\\Program ' 'Files\\Common Files\\Oracle\\Java\\javapath;C:\\Program Files (x86)\\Common ' 'Files\\Oracle\\Java\\javapath;C:\\Program Files\\PHP\\v7.4;C:\\Program ' 'Files\\PHP\\v8.0;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program ' 'Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\Program Files\\NVIDIA ' 'Corporation\\NVIDIA NvDLISR;C:\\Program Files\\Microsoft SQL Server\\Client ' 'SDK\\ODBC\\170\\Tools\\Binn\\;C:\\Program ' 'Files\\dotnet\\;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Program ' 'Files\\nodejs\\;C:\\ProgramData\\chocolatey\\bin;C:\\Users\\starr\\AppData\\Local\\Programs\\Python\\Python38-32\\Scripts\\;C:\\Users\\starr\\AppData\\Local\\Programs\\Python\\Python38-32\\;C:\\Users\\starr\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\starr\\.dotnet\\tools;C:\\Users\\starr\\.dotnet\\tools;C:\\Users\\starr\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\s;C:\\Program ' 'Files\\Calibre2\\;C:\\Program ' 'Files\\Git\\cmd;C:\\Users\\starr\\AppData\\Roaming\\Python\\Python311\\Scripts;C:\\Users\\starr\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\starr\\.dotnet\\tools;C:\\Users\\starr\\.dotnet\\tools;C:\\Users\\starr\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\starr\\AppData\\Roaming\\npm;C:\\Users\\starr\\AppData\\Local\\Programs\\Microsoft ' 'VS Code\\bin')

PATHEXT

'.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW;.CPL'

PATH_INFO

'/home/'

PROCESSOR_ARCHITECTURE

'AMD64'

PROCESSOR_IDENTIFIER

'Intel64 Family 6 Model 158 Stepping 10, GenuineIntel'

PROCESSOR_LEVEL

'6'

PROCESSOR_REVISION

'9e0a'

PROGRAMDATA

'C:\\ProgramData'

PROGRAMFILES

'C:\\Program Files'

PROGRAMFILES(X86)

'C:\\Program Files (x86)'

PROGRAMW6432

'C:\\Program Files'

PSMODULEPATH

('C:\\Users\\starr\\OneDrive\\Documents\\WindowsPowerShell\\Modules;C:\\Program ' 'Files\\WindowsPowerShell\\Modules;C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules')

PUBLIC

'C:\\Users\\Public'

QUERY_STRING

''

REMOTE_ADDR

'127.0.0.1'

REMOTE_HOST

''

REQUEST_METHOD

'GET'

RUN_MAIN

'true'

SCRIPT_NAME

''

SERVER_NAME

'Daffy'

SERVER_PORT

'8000'

SERVER_PROTOCOL

'HTTP/1.1'

SERVER_SOFTWARE

'WSGIServer/0.2'

SESSIONNAME

'Console'

SYSTEMDRIVE

'C:'

SYSTEMROOT

'C:\\WINDOWS'

TEMP

'C:\\Users\\starr\\AppData\\Local\\Temp'

TERM_PROGRAM

'vscode'

TERM_PROGRAM_VERSION

'1.75.1'

TMP

'C:\\Users\\starr\\AppData\\Local\\Temp'

USERDOMAIN

'DAFFY'

USERDOMAIN_ROAMINGPROFILE

'DAFFY'

USERNAME

'starr'

USERPROFILE

'C:\\Users\\starr'

VIRTUAL_ENV

'C:\\Users\\starr\\Code\\pet_memorial\\.venv'

VIRTUAL_ENV_PROMPT

'.venv'

VSCODE_GIT_ASKPASS_EXTRA_ARGS

'********************'

VSCODE_GIT_ASKPASS_MAIN

'********************'

VSCODE_GIT_ASKPASS_NODE

'********************'

VSCODE_GIT_IPC_HANDLE

'\\\\.\\pipe\\vscode-git-74a970d2f2-sock'

VSCODE_INJECTION

'1'

WINDIR

'C:\\WINDOWS'

ZES_ENABLE_SYSMAN

'1'

_OLD_VIRTUAL_PATH

('C:\\Program Files\\Python311\\Scripts\\;C:\\Program ' 'Files\\Python311\\;C:\\Program Files\\Common ' 'Files\\Oracle\\Java\\javapath;C:\\Program Files (x86)\\Common ' 'Files\\Oracle\\Java\\javapath;C:\\Program Files\\PHP\\v7.4;C:\\Program ' 'Files\\PHP\\v8.0;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program ' 'Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\Program Files\\NVIDIA ' 'Corporation\\NVIDIA NvDLISR;C:\\Program Files\\Microsoft SQL Server\\Client ' 'SDK\\ODBC\\170\\Tools\\Binn\\;C:\\Program ' 'Files\\dotnet\\;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Program ' 'Files\\nodejs\\;C:\\ProgramData\\chocolatey\\bin;C:\\Users\\starr\\AppData\\Local\\Programs\\Python\\Python38-32\\Scripts\\;C:\\Users\\starr\\AppData\\Local\\Programs\\Python\\Python38-32\\;C:\\Users\\starr\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\starr\\.dotnet\\tools;C:\\Users\\starr\\.dotnet\\tools;C:\\Users\\starr\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\s;C:\\Program ' 'Files\\Calibre2\\;C:\\Program ' 'Files\\Git\\cmd;C:\\Users\\starr\\AppData\\Roaming\\Python\\Python311\\Scripts;C:\\Users\\starr\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\starr\\.dotnet\\tools;C:\\Users\\starr\\.dotnet\\tools;C:\\Users\\starr\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\starr\\AppData\\Roaming\\npm;C:\\Users\\starr\\AppData\\Local\\Programs\\Microsoft ' 'VS Code\\bin')

wsgi.errors

<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>

wsgi.file_wrapper

<class 'wsgiref.util.FileWrapper'>

wsgi.input

<django.core.handlers.wsgi.LimitedStream object at 0x0000019326BFBA50>

wsgi.multiprocess

False

wsgi.multithread

True

wsgi.run_once

False

wsgi.url_scheme

'http'

wsgi.version

(1, 0)
Settings Using settings module pet_memorial.settings
Setting

Value

ABSOLUTE_URL_OVERRIDES

{}

ADMINS

[]

ALLOWED_HOSTS

[]

APPEND_SLASH

True

AUTHENTICATION_BACKENDS

['django.contrib.auth.backends.ModelBackend']

AUTH_PASSWORD_VALIDATORS

'********************'

AUTH_USER_MODEL

'auth.User'

BASE_DIR

'C:\\Users\\starr\\Code\\pet_memorial'

CACHES

{'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}

CACHE_MIDDLEWARE_ALIAS

'default'

CACHE_MIDDLEWARE_KEY_PREFIX

'********************'

CACHE_MIDDLEWARE_SECONDS

600

CSRF_COOKIE_AGE

31449600

CSRF_COOKIE_DOMAIN

None

CSRF_COOKIE_HTTPONLY

False

CSRF_COOKIE_MASKED

False

CSRF_COOKIE_NAME

'csrftoken'

CSRF_COOKIE_PATH

'/'

CSRF_COOKIE_SAMESITE

'Lax'

CSRF_COOKIE_SECURE

False

CSRF_FAILURE_VIEW

'django.views.csrf.csrf_failure'

CSRF_HEADER_NAME

'HTTP_X_CSRFTOKEN'

CSRF_TRUSTED_ORIGINS

[]

CSRF_USE_SESSIONS

False

DATABASES

{'default': {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_HEALTH_CHECKS': False, 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.sqlite3', 'HOST': '', 'NAME': 'C:\\Users\\starr\\Code\\pet_memorial\\db.sqlite3', 'OPTIONS': {}, 'PASSWORD': '********************', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': ''}}

DATABASE_ROUTERS

[]

DATA_UPLOAD_MAX_MEMORY_SIZE

2621440

DATA_UPLOAD_MAX_NUMBER_FIELDS

1000

DATA_UPLOAD_MAX_NUMBER_FILES

100

DATETIME_FORMAT

'N j, Y, P'

DATETIME_INPUT_FORMATS

['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M:%S.%f', '%m/%d/%Y %H:%M', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M:%S.%f', '%m/%d/%y %H:%M']

DATE_FORMAT

'N j, Y'

DATE_INPUT_FORMATS

['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%b %d %Y', '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d %Y', '%B %d, %Y', '%d %B %Y', '%d %B, %Y']

DEBUG

True

DEBUG_PROPAGATE_EXCEPTIONS

False

DECIMAL_SEPARATOR

'.'

DEFAULT_AUTO_FIELD

'django.db.models.AutoField'

DEFAULT_CHARSET

'utf-8'

DEFAULT_EXCEPTION_REPORTER

'django.views.debug.ExceptionReporter'

DEFAULT_EXCEPTION_REPORTER_FILTER

'django.views.debug.SafeExceptionReporterFilter'

DEFAULT_FILE_STORAGE

'django.core.files.storage.FileSystemStorage'

DEFAULT_FROM_EMAIL

'webmaster@localhost'

DEFAULT_INDEX_TABLESPACE

''

DEFAULT_TABLESPACE

''

DISALLOWED_USER_AGENTS

[]

EMAIL_BACKEND

'django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST

'localhost'

EMAIL_HOST_PASSWORD

'********************'

EMAIL_HOST_USER

''

EMAIL_PORT

25

EMAIL_SSL_CERTFILE

None

EMAIL_SSL_KEYFILE

'********************'

EMAIL_SUBJECT_PREFIX

'[Django] '

EMAIL_TIMEOUT

None

EMAIL_USE_LOCALTIME

False

EMAIL_USE_SSL

False

EMAIL_USE_TLS

False

FILE_UPLOAD_DIRECTORY_PERMISSIONS

None

FILE_UPLOAD_HANDLERS

['django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler']

FILE_UPLOAD_MAX_MEMORY_SIZE

2621440

FILE_UPLOAD_PERMISSIONS

420

FILE_UPLOAD_TEMP_DIR

None

FIRST_DAY_OF_WEEK

0

FIXTURE_DIRS

[]

FORCE_SCRIPT_NAME

None

FORMAT_MODULE_PATH

None

FORM_RENDERER

'django.forms.renderers.DjangoTemplates'

IGNORABLE_404_URLS

[]

INSTALLED_APPS

['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pet_profile']

INTERNAL_IPS

[]

LANGUAGES

[('af', 'Afrikaans'), ('ar', 'Arabic'), ('ar-dz', 'Algerian Arabic'), ('ast', 'Asturian'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('be', 'Belarusian'), ('bn', 'Bengali'), ('br', 'Breton'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('dsb', 'Lower Sorbian'), ('el', 'Greek'), ('en', 'English'), ('en-au', 'Australian English'), ('en-gb', 'British English'), ('eo', 'Esperanto'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-co', 'Colombian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('es-ve', 'Venezuelan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy', 'Frisian'), ('ga', 'Irish'), ('gd', 'Scottish Gaelic'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hsb', 'Upper Sorbian'), ('hu', 'Hungarian'), ('hy', 'Armenian'), ('ia', 'Interlingua'), ('id', 'Indonesian'), ('ig', 'Igbo'), ('io', 'Ido'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('kab', 'Kabyle'), ('kk', 'Kazakh'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('ky', 'Kyrgyz'), ('lb', 'Luxembourgish'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('mr', 'Marathi'), ('ms', 'Malay'), ('my', 'Burmese'), ('nb', 'Norwegian Bokmål'), ('ne', 'Nepali'), ('nl', 'Dutch'), ('nn', 'Norwegian Nynorsk'), ('os', 'Ossetic'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('sw', 'Swahili'), ('ta', 'Tamil'), ('te', 'Telugu'), ('tg', 'Tajik'), ('th', 'Thai'), ('tk', 'Turkmen'), ('tr', 'Turkish'), ('tt', 'Tatar'), ('udm', 'Udmurt'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('uz', 'Uzbek'), ('vi', 'Vietnamese'), ('zh-hans', 'Simplified Chinese'), ('zh-hant', 'Traditional Chinese')]

LANGUAGES_BIDI

['he', 'ar', 'ar-dz', 'fa', 'ur']

LANGUAGE_CODE

'en-us'

LANGUAGE_COOKIE_AGE

None

LANGUAGE_COOKIE_DOMAIN

None

LANGUAGE_COOKIE_HTTPONLY

False

LANGUAGE_COOKIE_NAME

'django_language'

LANGUAGE_COOKIE_PATH

'/'

LANGUAGE_COOKIE_SAMESITE

None

LANGUAGE_COOKIE_SECURE

False

LOCALE_PATHS

[]

LOGGING

{}

LOGGING_CONFIG

'logging.config.dictConfig'

LOGIN_REDIRECT_URL

'/accounts/profile/'

LOGIN_URL

'/accounts/login/'

LOGOUT_REDIRECT_URL

None

MANAGERS

[]

MEDIA_ROOT

''

MEDIA_URL

'/'

MESSAGE_STORAGE

'django.contrib.messages.storage.fallback.FallbackStorage'

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

MIGRATION_MODULES

{}

MONTH_DAY_FORMAT

'F j'

NUMBER_GROUPING

0

PASSWORD_HASHERS

'********************'

PASSWORD_RESET_TIMEOUT

'********************'

PREPEND_WWW

False

ROOT_URLCONF

'pet_memorial.urls'

SECRET_KEY

'********************'

SECRET_KEY_FALLBACKS

'********************'

SECURE_CONTENT_TYPE_NOSNIFF

True

SECURE_CROSS_ORIGIN_OPENER_POLICY

'same-origin'

SECURE_HSTS_INCLUDE_SUBDOMAINS

False

SECURE_HSTS_PRELOAD

False

SECURE_HSTS_SECONDS

0

SECURE_PROXY_SSL_HEADER

None

SECURE_REDIRECT_EXEMPT

[]

SECURE_REFERRER_POLICY

'same-origin'

SECURE_SSL_HOST

None

SECURE_SSL_REDIRECT

False

SERVER_EMAIL

'root@localhost'

SESSION_CACHE_ALIAS

'default'

SESSION_COOKIE_AGE

1209600

SESSION_COOKIE_DOMAIN

None

SESSION_COOKIE_HTTPONLY

True

SESSION_COOKIE_NAME

'sessionid'

SESSION_COOKIE_PATH

'/'

SESSION_COOKIE_SAMESITE

'Lax'

SESSION_COOKIE_SECURE

False

SESSION_ENGINE

'django.contrib.sessions.backends.db'

SESSION_EXPIRE_AT_BROWSER_CLOSE

False

SESSION_FILE_PATH

None

SESSION_SAVE_EVERY_REQUEST

False

SESSION_SERIALIZER

'django.contrib.sessions.serializers.JSONSerializer'

SETTINGS_MODULE

'pet_memorial.settings'

SHORT_DATETIME_FORMAT

'm/d/Y P'

SHORT_DATE_FORMAT

'm/d/Y'

SIGNING_BACKEND

'django.core.signing.TimestampSigner'

SILENCED_SYSTEM_CHECKS

[]

STATICFILES_DIRS

[]

STATICFILES_FINDERS

['django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder']

STATICFILES_STORAGE

'django.contrib.staticfiles.storage.StaticFilesStorage'

STATIC_ROOT

None

STATIC_URL

'/static/'

TEMPLATES

[{'APP_DIRS': True, 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['C:\\Users\\starr\\Code\\pet_memorial\\pet_memorial/templates/pet_memorial/', 'C:\\Users\\starr\\Code\\pet_memorial\\pet_profile/templates/pet_profile/'], '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']}}]

TEMPLATE_APP_DIR

'C:\\Users\\starr\\Code\\pet_memorial\\pet_profile/templates/pet_profile/'

TEMPLATE_PROJECT_DIR

'C:\\Users\\starr\\Code\\pet_memorial\\pet_memorial/templates/pet_memorial/'

TEST_NON_SERIALIZED_APPS

[]

TEST_RUNNER

'django.test.runner.DiscoverRunner'

THOUSAND_SEPARATOR

','

TIME_FORMAT

'P'

TIME_INPUT_FORMATS

['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']

TIME_ZONE

'UTC'

USE_DEPRECATED_PYTZ

False

USE_I18N

True

USE_L10N

True

USE_THOUSAND_SEPARATOR

False

USE_TZ

True

USE_X_FORWARDED_HOST

False

USE_X_FORWARDED_PORT

False

WSGI_APPLICATION

'pet_memorial.wsgi.application'

X_FRAME_OPTIONS

'DENY'

YEAR_MONTH_FORMAT

'F Y'

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 page generated by the handler for this status code.



I understand my code isn't the cleanest, but I don't see why the core mechanism of url template tagging to a url named in one of the urls.py files isn't working.

Any help is appreciated.

Michael

Michael Starr

unread,
Feb 28, 2023, 6:35:00 PM2/28/23
to Django users
I have found some resources in the mangy mess of disorganized misinformation known as the internet
{% extends "base.html" %}
{% block header %}
   
{% endblock %}
{% block content %}
    <a href="{% url 'owner_profile' slug=owner.slug %}">test</a>
{% endblock %}

is my new home.html template. Note that I am trying to pass in slug by delineating explicitly "slug=" and  "owner" comes from the parameter name in the view (or should)

class PetOwnerProfileView(DetailView):
    model = PetOwner
    context_object_name = "owner"
    template_name = "pet_owner_profile.html"

as you can see, I have "context_oibject_name = "owner"". Which is correct syntax, I have tested it and found it in numerous resources.

What's strange is there are nearly NO RESOURCES on google regarding how to simply pass in a slug as a parameter to a url template tag in django.

This is the only relevant website I found:


to quote:

i want to add slug in url using django like this <a href="{% url 'base:tutorial-page' p.slug p.slug2 %}" </a> i dont really know how to pass in double slug in the url for example: i want to access the html page before going to the tutorial page related to html.

getting-started.html

{% for p in prglangcat %}> {{ p.title }} <a href="{% url 'base:tutorial-page' p.slug p.slug %}" </a> {% endfor %}

views.py

def gettingStarted(request): prglangcat = ProgrammingLanguagesCategory.objects.all() context = { 'prglangcat': prglangcat } return render(request, 'base/getting-started.html', context) def programmingLanguageTutorial(request, prg_slug, prglangcat): prglangcat = ProgrammingLanguagesCategory.objects.get(slug=prglangcat_slug) prglangtut = ProgrammingLanguageTutorial.objects.get(slug=prg_slug, prglangcat=prglangcat) context = { 'prglangtut': prglangtut } return render(request, 'base/tutorial-page.html', context)

models.py

class ProgrammingLanguagesCategory(models.Model): title = models.CharField(max_length=100) icon = models.ImageField(upload_to='programming-category', default="default.jpg") description = models.TextField(default="Learn ...") slug = models.SlugField(max_length=100, unique=True) def get_absolute_url(self): return reverse('programming-languages-category', args=[self.slug]) def __str__(self): return self.title class ProgrammingLanguageTutorial(models.Model): prglangcat = models.ForeignKey(ProgrammingLanguagesCategory, on_delete=models.CASCADE, null=True) slug = models.SlugField(max_length=10000, unique=True) title = models.CharField(max_length=10000) description = models.TextField(null=True) image = models.ImageField(upload_to='Tutorial Image', default="default.jpg", null=True) code_snippet = models.CharField(max_length=1000000000, null=True, blank=True) video_url = models.URLField(null=True) views = models.IntegerField(default=0) def __str__(self): return self.title

urls.py

app_name = 'base' urlpatterns = [ path('', views.index, name="index"), path('getting-started/', views.gettingStarted, name="getting-started"), path('getting-started/<slug:prglangcat_slug>/<slug:prg_slug>', views.programmingLanguageTutorial, name="tutorial-page"), ]

taceback

NoReverseMatch at /getting-started/ Reverse for 'tutorial-page' with no arguments not found. 1 pattern(s) tried: ['getting\\-started/(?P<prglangcat_slug>[-a-zA-Z0-9_]+)/(?P<prg_slug>[-a-zA-Z0-9_]+)

what i have tried
{% url 'base:tutorial-page' prg_slug=p.prg_slug prglangcat_slug=p.prglangcat_slug%}

Perfect. Now then - how would you refer to a field named slug in that same object? Finally then, that is what you need to use in your template to access the slug field in the url tag, if in your template you have an object named p that is referring to an instance of ProgrammingLanguagesCategory.

But there's no note as to whether the [context variable name].[slugname] is the correct way to do it or not, in the end.
They're sort of roundabout and quizzical in that they ask more questions instead of actually helping or answering them. Very Yoda, having a good time I see they are.

But this doesn't work. I now get the error:
NoReverseMatch at /home/ Reverse for 'owner_profile' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['owner/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
Request Method:

GET

Request URL:

http://127.0.0.1:8000/home/

Django Version:

4.1.7

Exception Type:

NoReverseMatch

Exception Value:

Reverse for 'owner_profile' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['owner/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']

Exception Location:

C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix

Raised during:

pet_memorial.views.HomeView

Python Executable:

C:\Users\starr\Code\pet_memorial\.venv\Scripts\python.exe

Python Version:

3.11.2

Python Path:

['C:\\Users\\starr\\Code\\pet_memorial', 'C:\\Program Files\\Python311\\python311.zip', 'C:\\Program Files\\Python311\\DLLs', 'C:\\Program Files\\Python311\\Lib', 'C:\\Program Files\\Python311', 'C:\\Users\\starr\\Code\\pet_memorial\\.venv', 'C:\\Users\\starr\\Code\\pet_memorial\\.venv\\Lib\\site-packages']

Server time:

Tue, 28 Feb 2023 23:12:12 +0000
Error during template rendering

In template C:\Users\starr\Code\pet_memorial\pet_memorial\templates\pet_memorial\home.html, error at line 6

Reverse for 'owner_profile' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['owner/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
1

{% extends "base.html" %}

2

{% block header %}

3


4

{% endblock %}

5

{% block content %}

6

<a href="{% url 'owner_profile' slug=owner.slug %}">test</a>

7

{% endblock %}
COOKIES
Variable

Value

csrftoken

'l6JTjHi46PwSI1jYALvcH9SSo517mqhE'

sessionid

'nc60k9j7w318bzh707je4ekwhfbszyvb'
META
Variable

Value

ALLUSERSPROFILE

'C:\\ProgramData'

APPDATA

'C:\\Users\\starr\\AppData\\Roaming'

CHOCOLATEYINSTALL

'C:\\ProgramData\\chocolatey'

CHOCOLATEYLASTPATHUPDATE

'132763030117094841'

CHROME_CRASHPAD_PIPE_NAME

'\\\\.\\pipe\\LOCAL\\crashpad_7356_VDJSPXLOEBBONWTJ'

COLORTERM

'truecolor'

COMMONPROGRAMFILES

'C:\\Program Files\\Common Files'

COMMONPROGRAMFILES(X86)

'C:\\Program Files (x86)\\Common Files'

COMMONPROGRAMW6432

'C:\\Program Files\\Common Files'

COMPUTERNAME

'DAFFY'

COMSPEC

'C:\\WINDOWS\\system32\\cmd.exe'

CONFIGSETROOT

'C:\\WINDOWS\\ConfigSetRoot'

CONTENT_LENGTH

''

CONTENT_TYPE

'text/plain'

CSRF_COOKIE

'l6JTjHi46PwSI1jYALvcH9SSo517mqhE'

DJANGO_SETTINGS_MODULE

'pet_memorial.settings'

DRIVERDATA

'C:\\Windows\\System32\\Drivers\\DriverData'

GATEWAY_INTERFACE

'CGI/1.1'

GIT_ASKPASS

'********************'

HOMEDRIVE

'C:'

HOMEPATH

'\\Users\\starr'

HTTP_ACCEPT

'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8'

HTTP_ACCEPT_ENCODING

'gzip, deflate, br'

HTTP_ACCEPT_LANGUAGE

'en-US,en;q=0.5'

HTTP_CONNECTION

'keep-alive'

HTTP_COOKIE

('csrftoken=l6JTjHi46PwSI1jYALvcH9SSo517mqhE; ' 'sessionid=nc60k9j7w318bzh707je4ekwhfbszyvb')

HTTP_HOST

'127.0.0.1:8000'

HTTP_SEC_FETCH_DEST

'document'

HTTP_SEC_FETCH_MODE

'navigate'

HTTP_SEC_FETCH_SITE

'none'

HTTP_SEC_FETCH_USER

'?1'

HTTP_SEC_GPC

'1'

HTTP_UPGRADE_INSECURE_REQUESTS

'1'

HTTP_USER_AGENT


LANG

'en_US.UTF-8'

LOCALAPPDATA


LOGONSERVER

'\\\\DAFFY'

NUMBER_OF_PROCESSORS

'12'

ONEDRIVE

'C:\\Users\\starr\\OneDrive'

ONEDRIVECONSUMER

'C:\\Users\\starr\\OneDrive'

ORIGINAL_XDG_CURRENT_DESKTOP

'undefined'

OS

'Windows_NT'

PATH


PATHEXT


PATH_INFO

'/home/'

PROCESSOR_ARCHITECTURE

'AMD64'

PROCESSOR_IDENTIFIER


PROCESSOR_LEVEL

'6'

PROCESSOR_REVISION

'9e0a'

PROGRAMDATA

'C:\\ProgramData'

PROGRAMFILES

'C:\\Program Files'

PROGRAMFILES(X86)

'C:\\Program Files (x86)'

PROGRAMW6432

'C:\\Program Files'

PSMODULEPATH


PUBLIC

'C:\\Users\\Public'

QUERY_STRING

''

REMOTE_ADDR

'127.0.0.1'

REMOTE_HOST

''

REQUEST_METHOD

'GET'

RUN_MAIN

'true'

SCRIPT_NAME

''

SERVER_NAME

'Daffy'

SERVER_PORT

'8000'

SERVER_PROTOCOL

'HTTP/1.1'

SERVER_SOFTWARE

'WSGIServer/0.2'

SESSIONNAME

'Console'

SYSTEMDRIVE

'C:'

SYSTEMROOT

'C:\\WINDOWS'

TEMP


TERM_PROGRAM

'vscode'

TERM_PROGRAM_VERSION

'1.75.1'

TMP


USERDOMAIN

'DAFFY'

USERDOMAIN_ROAMINGPROFILE

'DAFFY'

USERNAME

'starr'

USERPROFILE

'C:\\Users\\starr'

VIRTUAL_ENV


VIRTUAL_ENV_PROMPT

'.venv'

VSCODE_GIT_ASKPASS_EXTRA_ARGS

'********************'

VSCODE_GIT_ASKPASS_MAIN

'********************'

VSCODE_GIT_ASKPASS_NODE

'********************'

VSCODE_GIT_IPC_HANDLE

'\\\\.\\pipe\\vscode-git-74a970d2f2-sock'

VSCODE_INJECTION

'1'

WINDIR

'C:\\WINDOWS'

ZES_ENABLE_SYSMAN

'1'

_OLD_VIRTUAL_PATH


wsgi.errors


wsgi.file_wrapper

<class 'wsgiref.util.FileWrapper'>

wsgi.input

<django.core.handlers.wsgi.LimitedStream object at 0x000001FC91517410>

wsgi.multiprocess

False

wsgi.multithread

True

wsgi.run_once

False

wsgi.url_scheme

'http'

wsgi.version

(1, 0)
Settings Using settings module pet_memorial.settings
Setting

Value

ABSOLUTE_URL_OVERRIDES

{}

ADMINS

[]

ALLOWED_HOSTS

[]

APPEND_SLASH

True

AUTHENTICATION_BACKENDS

['django.contrib.auth.backends.ModelBackend']

AUTH_PASSWORD_VALIDATORS

'********************'

AUTH_USER_MODEL

'auth.User'

BASE_DIR


CACHES

{'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}

CACHE_MIDDLEWARE_ALIAS

'default'

CACHE_MIDDLEWARE_KEY_PREFIX

'********************'

CACHE_MIDDLEWARE_SECONDS

600

CSRF_COOKIE_AGE

31449600

CSRF_COOKIE_DOMAIN

None

CSRF_COOKIE_HTTPONLY

False

CSRF_COOKIE_MASKED

False

CSRF_COOKIE_NAME

'csrftoken'

CSRF_COOKIE_PATH

'/'

CSRF_COOKIE_SAMESITE

'Lax'

CSRF_COOKIE_SECURE

False

CSRF_FAILURE_VIEW

'django.views.csrf.csrf_failure'

CSRF_HEADER_NAME

'HTTP_X_CSRFTOKEN'

CSRF_TRUSTED_ORIGINS

[]

CSRF_USE_SESSIONS

False

DATABASES


DATABASE_ROUTERS

[]

DATA_UPLOAD_MAX_MEMORY_SIZE

2621440

DATA_UPLOAD_MAX_NUMBER_FIELDS

1000

DATA_UPLOAD_MAX_NUMBER_FILES

100

DATETIME_FORMAT

'N j, Y, P'

DATETIME_INPUT_FORMATS


DATE_FORMAT

'N j, Y'

DATE_INPUT_FORMATS


DEBUG

True

DEBUG_PROPAGATE_EXCEPTIONS

False

DECIMAL_SEPARATOR

'.'

DEFAULT_AUTO_FIELD

'django.db.models.AutoField'

DEFAULT_CHARSET

'utf-8'

DEFAULT_EXCEPTION_REPORTER

'django.views.debug.ExceptionReporter'

DEFAULT_EXCEPTION_REPORTER_FILTER

'django.views.debug.SafeExceptionReporterFilter'

DEFAULT_FILE_STORAGE

'django.core.files.storage.FileSystemStorage'

DEFAULT_FROM_EMAIL

'webmaster@localhost'

DEFAULT_INDEX_TABLESPACE

''

DEFAULT_TABLESPACE

''

DISALLOWED_USER_AGENTS

[]

EMAIL_BACKEND

'django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST

'localhost'

EMAIL_HOST_PASSWORD

'********************'

EMAIL_HOST_USER

''

EMAIL_PORT

25

EMAIL_SSL_CERTFILE

None

EMAIL_SSL_KEYFILE

'********************'

EMAIL_SUBJECT_PREFIX

'[Django] '

EMAIL_TIMEOUT

None

EMAIL_USE_LOCALTIME

False

EMAIL_USE_SSL

False

EMAIL_USE_TLS

False

FILE_UPLOAD_DIRECTORY_PERMISSIONS

None

FILE_UPLOAD_HANDLERS

['django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler']

FILE_UPLOAD_MAX_MEMORY_SIZE

2621440

FILE_UPLOAD_PERMISSIONS

420

FILE_UPLOAD_TEMP_DIR

None

FIRST_DAY_OF_WEEK

0

FIXTURE_DIRS

[]

FORCE_SCRIPT_NAME

None

FORMAT_MODULE_PATH

None

FORM_RENDERER

'django.forms.renderers.DjangoTemplates'

IGNORABLE_404_URLS

[]

INSTALLED_APPS


INTERNAL_IPS

[]

LANGUAGES


LANGUAGES_BIDI


LANGUAGE_CODE

'en-us'

LANGUAGE_COOKIE_AGE

None

LANGUAGE_COOKIE_DOMAIN

None

LANGUAGE_COOKIE_HTTPONLY

False

LANGUAGE_COOKIE_NAME

'django_language'

LANGUAGE_COOKIE_PATH

'/'

LANGUAGE_COOKIE_SAMESITE

None

LANGUAGE_COOKIE_SECURE

False

LOCALE_PATHS

[]

LOGGING

{}

LOGGING_CONFIG

'logging.config.dictConfig'

LOGIN_REDIRECT_URL

'/accounts/profile/'

LOGIN_URL

'/accounts/login/'

LOGOUT_REDIRECT_URL

None

MANAGERS

[]

MEDIA_ROOT

''

MEDIA_URL

'/'

MESSAGE_STORAGE

'django.contrib.messages.storage.fallback.FallbackStorage'

MIDDLEWARE


MIGRATION_MODULES

{}

MONTH_DAY_FORMAT

'F j'

NUMBER_GROUPING

0

PASSWORD_HASHERS

'********************'

PASSWORD_RESET_TIMEOUT

'********************'

PREPEND_WWW

False

ROOT_URLCONF

'pet_memorial.urls'

SECRET_KEY

'********************'

SECRET_KEY_FALLBACKS

'********************'

SECURE_CONTENT_TYPE_NOSNIFF

True

SECURE_CROSS_ORIGIN_OPENER_POLICY

'same-origin'

SECURE_HSTS_INCLUDE_SUBDOMAINS

False

SECURE_HSTS_PRELOAD

False

SECURE_HSTS_SECONDS

0

SECURE_PROXY_SSL_HEADER

None

SECURE_REDIRECT_EXEMPT

[]

SECURE_REFERRER_POLICY

'same-origin'

SECURE_SSL_HOST

None

SECURE_SSL_REDIRECT

False

SERVER_EMAIL

'root@localhost'

SESSION_CACHE_ALIAS

'default'

SESSION_COOKIE_AGE

1209600

SESSION_COOKIE_DOMAIN

None

SESSION_COOKIE_HTTPONLY

True

SESSION_COOKIE_NAME

'sessionid'

SESSION_COOKIE_PATH

'/'

SESSION_COOKIE_SAMESITE

'Lax'

SESSION_COOKIE_SECURE

False

SESSION_ENGINE

'django.contrib.sessions.backends.db'

SESSION_EXPIRE_AT_BROWSER_CLOSE

False

SESSION_FILE_PATH

None

SESSION_SAVE_EVERY_REQUEST

False

SESSION_SERIALIZER

'django.contrib.sessions.serializers.JSONSerializer'

SETTINGS_MODULE

'pet_memorial.settings'

SHORT_DATETIME_FORMAT

'm/d/Y P'

SHORT_DATE_FORMAT

'm/d/Y'

SIGNING_BACKEND

'django.core.signing.TimestampSigner'

SILENCED_SYSTEM_CHECKS

[]

STATICFILES_DIRS

[]

STATICFILES_FINDERS

['django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder']

STATICFILES_STORAGE

'django.contrib.staticfiles.storage.StaticFilesStorage'

STATIC_ROOT

None

STATIC_URL

'/static/'

TEMPLATES


TEMPLATE_APP_DIR


TEMPLATE_PROJECT_DIR


TEST_NON_SERIALIZED_APPS

[]

TEST_RUNNER

'django.test.runner.DiscoverRunner'

THOUSAND_SEPARATOR

','

TIME_FORMAT

'P'

TIME_INPUT_FORMATS


TIME_ZONE

'UTC'

USE_DEPRECATED_PYTZ

False

USE_I18N

True

USE_L10N

True

USE_THOUSAND_SEPARATOR

False

USE_TZ

True

USE_X_FORWARDED_HOST

False

USE_X_FORWARDED_PORT

False

WSGI_APPLICATION

'pet_memorial.wsgi.application'

X_FRAME_OPTIONS

'DENY'

YEAR_MONTH_FORMAT

'F Y'


Key information in error:
Reverse for 'owner_profile' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['owner/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
Exception Location:

C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix

Raised during:

pet_memorial.views.HomeView


So at least it seems A) that I am passing in as slug= correctly, it recogniazes "keyword arguments '{'slug: ''}'.

However, I now see that it is rendering from the home view, not the pet owner profile view.

Now that question is: I don't know how to send the owner slug specifically information into home view context.
And I think
def get_context_data(self,*args, **kwargs):
        context = super(Intro, self).get_context_data(*args,**kwargs)
        context['users'] = YourModel.objects.all()
        return context
get_context_data is the answer. I've done this once before but apparently I didn't remember or write it down and deleted my files.

So my code for the HOME view (NOT pet owner detail view) is now
from django.views.generic import TemplateView
from pet_profile.models import PetOwner

class HomeView(TemplateView):
    template_name = "home.html"
    def get_context_data(self, *args, **kwargs):
        context['pet_owner'] = PetOwner.objects.all()
        return context

but I am now getting an error that context is not defined. Seems the framework doesn't want to let go, and insists on breakin gat all costs!

This reference
recommends a circular reference of assigning context to get_context_data, inside of get_context_data. Bad idea. Won't even try it.

Or maybe not. I guess pairing it with super. fixes it.

context = super().get_context_data(**kwargs)

I'm still not sure how super works, despite reading the documentation. It's too esoteric for me to understand. But that's for another day.

Once again NoReverseMatch at /home/ Reverse for 'owner_profile' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['owner/(?P<slug>[-a-zA-Z0-9_]+)/\\Z'].
Does it need to be in quotes? Why am i guessing? Why doesn't the documentation delineate all this? Frustrating.

Wiht quotes:

NoReverseMatch at /home/ Reverse for 'owner_profile' with keyword arguments '{'slug': 'pet_owner.slug'}' not found. 1 pattern(s) tried: ['owner/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']

At least it recognizes the parameter now. Sort of. It doesn't find it though. I don't know why. I expressed it in the home view's context dictionary, so it should be found!


And that's as far as I've gotten. I don't know what else to do. The google searches are starting to require semantic understanding, and google doesn't do that. I think a limit has been reached.

Michael

Michael Starr

unread,
Feb 28, 2023, 6:49:43 PM2/28/23
to Django users
{% extends "base.html" %}
{% block header %}
   
{% endblock %}
{% block content %}
    <a href="{% url 'owner_profile' slug=pet_owner %}">test</a>
{% endblock %}

yields progress with

NoReverseMatch at /home/ Reverse for 'owner_profile' with keyword arguments '{'slug': <QuerySet [<PetOwner: Jasper Morello>]>}' not found. 1 pattern(s) tried: ['owner/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
Request Method:

GET

Request URL:

http://127.0.0.1:8000/home/

Django Version:

4.1.7

Exception Type:

NoReverseMatch

Exception Value:

Reverse for 'owner_profile' with keyword arguments '{'slug': <QuerySet [<PetOwner: Jasper Morello>]>}' not found. 1 pattern(s) tried: ['owner/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']

Exception Location:

C:\Users\starr\Code\pet_memorial\.venv\Lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix

Raised during:

pet_memorial.views.HomeView

Python Executable:

C:\Users\starr\Code\pet_memorial\.venv\Scripts\python.exe

Python Version:

3.11.2

Python Path:

['C:\\Users\\starr\\Code\\pet_memorial', 'C:\\Program Files\\Python311\\python311.zip', 'C:\\Program Files\\Python311\\DLLs', 'C:\\Program Files\\Python311\\Lib', 'C:\\Program Files\\Python311', 'C:\\Users\\starr\\Code\\pet_memorial\\.venv', 'C:\\Users\\starr\\Code\\pet_memorial\\.venv\\Lib\\site-packages']

Server time:

Tue, 28 Feb 2023 23:45:05 +0000


this is better because it indicates that the context dictionary does understand the PetOwner object (I have a pet owner named "Jasper Morello").

Try the name parameter:
NoReverseMatch at /home/ Reverse for 'owner_profile' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['owner/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']

So the bug seems to be that any parameter of the context dictionary object (the object being recognized), the parameters can not be referenced, and/or I am using improper syntax to reference them. I don't know what else to do.

TemplateSyntaxError at /home/ Could not parse the remainder: '[name]' from 'pet_owner[name]'

for

{% extends "base.html" %}
{% block header %}
   
{% endblock %}
{% block content %}
    <a href="{% url 'owner_profile' slug=pet_owner[name] %}">test</a>
{% endblock %}

So I guess, if anyone knows how to reference context dictionary parameters (sub-objects) in a View from the template, let me know. I'll keep digging.

Michael

Michael Starr

unread,
Feb 28, 2023, 6:52:26 PM2/28/23
to Django users
To clarify,
<a href="{% url '<url name>' <parameter, such as slug>=<view context object name>.<context object parameter> %}">blah blah</a>
does not work. And I don't know why.

.<context object parameter>

is not recognized, to be specific.

Michael

Michael Starr

unread,
Feb 28, 2023, 6:54:21 PM2/28/23
to Django users
I am not doing anything wrong. But it doesn't work.
I would browse through the docs, I think I will, but for now I am tired of the bs from the framework that is for perfectionists with deadlines.

More like for perfectionists who like agonizing over unspecified errors ad nauseum.

Michael

Michael Starr

unread,
Feb 28, 2023, 6:55:50 PM2/28/23
to Django users

Michael Starr

unread,
Mar 1, 2023, 1:05:48 AM3/1/23
to Django users
I just now realized I am returning a list of pet owners, not one pet owner, and as such no parameter will be valid. I have to either loop through the list, or filter it in the view.

Will update on results.

Michael

Michael Starr

unread,
Mar 1, 2023, 1:08:24 AM3/1/23
to Django users
Yeah it works now.

Here's the final code:

(or some of it anyway)

home.html
{% extends "base.html" %}
{% block header %}
   
{% endblock %}
{% block content %}
    {% for pet_owner in pet_owners %}
        <a href="{% url 'owner_profile' slug=pet_owner.slug %}">test</a>
    {% endfor %}
{% endblock %}

views.py
from django.views.generic import TemplateView
from pet_profile.models import PetOwner

class HomeView(TemplateView):
    template_name = "home.html"
    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(**kwargs)
        context['pet_owners'] = PetOwner.objects.all()
        return context



Thanks for being a landing place to hash out my issues. Looking forward to help from others when needed next time.

Michael

Michael Starr

unread,
Mar 1, 2023, 1:22:11 AM3/1/23
to Django users
pet_owner.profile.html template
{% extends "base.html" %}
{% block header %}
{% endblock %}
{% block content %}
    {{ owner.name }}
    {{ owner.age }}
    {{ owner.location }}
    {{ owner.profile_photo }}
    {% for pet in owner.pets.all %}
        {{ pet.name }}
        {{ pet.animaltype }}
        {{ pet.age }}
        {{ pet.profile_photo }}
    {% endfor %}
{% endblock %}

Michael Starr

unread,
Mar 1, 2023, 1:29:32 AM3/1/23
to Django users
And I do apologize for hating on the django docs. The Index at the docs is super useful.
Michael
Reply all
Reply to author
Forward
0 new messages