0
votes

I have a model, Position, which I have created a detail view to view each individual position.

views.py

def position_detail_view(request, id=None):

    position = get_object_or_404(Position, id=id)

    context= {
        'object': position,
    }

    return render(request, 'positions/position_detail.html', context)

positions/urls.py

from django.urls import path, include
from .views import position_list_view, position_detail_view

urlpatterns = [
    path('', position_list_view),
    path('<int:id>', position_detail_view, name='detail')
]

When I go to http://localhost:8000/apply/1/, where the id=1, I get a Page Not Found 404 Error. However, with any other id, the page loads just fine. Any ideas on why the first id in the model gives a 404 error?

Edit 1: Traceback Error

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

admin/ [name='home'] apply/application/ apply/ apply/ [name='detail'] The current path, apply/1/, didn't match any of these.

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.

1
are you sure object with id 1 exists in database? - shafik
@ShafikurRahman Yes, I just checked the database and the admin to confirm that there is an object with id=1. - express_v2
add your full error traceback - shafik
Now in the post. - express_v2
change url path to path('/<int:id>/', position_detail_view, name='detail') - shafik

1 Answers

1
votes

Django get_object_or_404 works like below.

get_object_or_404(klass, *args, **kwargs)

Calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception. In your case, your URL path is not properly configured. Try to make changes this:

path('/<int:id>/', position_detail_view, name='detail')