pythondjangodjango-3.1

Page not found when trying to use Django url routing


So I've been trying to use django dynamic url routing but when I try to open the link, Django shows me that the page was not found (error 404).

Here's my urls.py:

from django.urls import path
from pages.views import home_view, contact_view
from products.views import (
    product_detail_view,
    product_create_view,
    render_initial_data,
    dynamic_lookup_view
    )

urlpatterns = [
    path('', home_view, name = 'home'),
    path('contact/', contact_view, name = 'contact'),
    path('product/<int:my_id>', dynamic_lookup_view, name='product'),
    path('create/', product_create_view),
    path('admin/', admin.site.urls),
]

Here's my views.py (Only included the main function which I'm trying to render right now):

from django.shortcuts import render
from .models import Product
#from .forms import ProductForm, RawProductForm
# Create your views here.

def dynamic_lookup_view(request, my_id):
    obj = Product.objects.get(id=my_id)
    context = {
        "object": obj
    }
    return render(request, "products/product_detail.html", context)

When I'm trying to open the /product/ I get the error. Can anyone tell me what I'm doing wrong?

This is the error:

Request Method: GET
Request URL:    http://127.0.0.1:8000/product/
Using the URLconf defined in trydjango.urls, Django tried these URL patterns, in this order:

[name='home']
contact/ [name='contact']
product/<int:my_id> [name='product']
admin/
The current path, product/, didn't match any of these.

Solution

  • You should use pk instead of id like this:

    obj = Product.objects.get(pk=my_id)
    

    Or you can use get_object_or_404 function.

    from django.shortcuts import get_object_or_404
    
    def my_view(request):
        obj = get_object_or_404(MyModel, pk=1)