Django 404 with existing database entry

Viewed 44

I'm quite new to django and currently working on my first unguided project. I've run into a problem which seems very unreasonable to me and can't tackle it myself.

Basically, I do get url pattern match, however get also 404 error that page is not found. I have tested it with various entries and the result is always the same - 404.

companies/urls.py

from . import views
from django.conf.urls import url

urlpatterns = [
    url(r'^company/(?P<pk>)', views.CompanyDetailView.as_view(), name='company-detail')
]

Main/urls.py

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


urlpatterns = [
    path('admin/', admin.site.urls),
    path('companies/', include('companies.urls'))
]

and here's the error message: *"Page not found (404) No company found matching the query Request Method: GET Request URL: http://127.0.0.1:8080/companies/company/F/ Raised by: companies.views.CompanyDetailView Using the URLconf defined in main.urls, Django tried these URL patterns, in this order:

admin/

companies/ ^company/(?P) [name='company-detail']

The current path, companies/company/F/, 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."*

Just to add, I can access the record from admin with url

http://127.0.0.1:8080/admin/companies/company/F/change/

Really lost here and question my sanity.

1 Answers

The regular expression part of the primary key is missing, for example:

urlpatterns = [
    url(r'^company/(?P<pk>.*)/$', views.CompanyDetailView.as_view(), name='company-detail')
]

If you work with a url(…) then it expects that for the parameters you add a regex to capture the value. If you do not specify any regex between the brackets, then the pattern is considered empty, and thus the parameter will be an empty string.

I don't know if pk is a good parameter name, since you pass items like F to it. perhaps this should be renamed to slug or something similar.


Note: As of , url(…) [Django-doc] is deprecated in favor of re_path(…) [Django-doc]. Furthermore a new syntax for paths has been introduced with path converters: you use path(…) [Django-doc] for that.

Related