Rene
Rene

Reputation: 400

Django 404: "No object instance found matching the query"

Despite the url arguments being accurate (as far as I can see), Django raises a 404 error when trying to access a specific detail view.

I'm trying to create a detail view for specific car instances in my project. I've just created a slug that passes each car's unique UUID into the url, but Django raises a 404 Error.

It can't find the specific instance, but the urls are accurate and the url accurately matches the id. Also, I'm clicking in from the ListView which works fine.

Corrected error screenshot Error screenshot in browser

id confirmation from admin page ID confirmation from object admin page. Note that it matches the above url.

models.py

class CarInstance(models.Model):
    ....
    id = models.UUIDField(primary_key=True, default=uuid.uuid4,
    help_text="Unique ID for this car")
    ...

    class Meta:
        ordering = ['date_added']

    def __str__(self):
        return f'{self.manufacturer} {self.car_model}'

    def get_absolute_url(self):
        return reverse('showroom:car-detail', args=[str(self.pk)])


urls.py


urlpatterns = [
    ...
    path('car/<slug:car_detail>/', views.CarDetailView.as_view(), name='car-detail')
]

views.py

class CarDetailView(generic.DetailView):
    model = CarInstance
    template_name = 'car_detail'
    slug_field = 'car_model'
    slug_url_kwarg = 'car_detail'

    def get_queryset(self):
         return CarInstance.objects.all()

Upvotes: 1

Views: 966

Answers (2)

Matthew Gaiser
Matthew Gaiser

Reputation: 4763

Your slug_field is not car_model, but rather id. You are trying to use the wrong thing to find the model.

I got your code to run by changing it to this. The normal caveats about having to make some assumptions apply, so please ask any questions you need to.

class CarDetailView(DetailView):
    model = CarInstance
    template_name = 'car_detail'
    slug_field = 'id'
    slug_url_kwarg = 'car_detail'

    def get_queryset(self):
         return CarInstance.objects.all()

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599590

You've defined your URL to take a slug, car_detail, and then told your view to use the value in that slug to look up in the car_model field. But then the URL you go to contains a UUID which you want to look up in the id field. Can you not see the disconnect?

If you want to look up by the ID field (ie the primary key), then do so:

path('car/<uuid:pk>/', views.CarDetailView.as_view(), name='car-detail')

and remove the slug_field and slug_url_kwarg from the view.

Upvotes: 3

Related Questions