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'
'C:\\Program Files (x86)\\Common Files'
'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
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.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
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
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