Why is a single product page not loading in Django project
I am trying to make an ecommerce project and I already set up products page, but It should load a product description page after goint to api/products/2 page, example(2 is a product id). views.py:
@api_view(['GET']) def getProduct(request, pk): product = None for i in products: if i['_id'] == pk: product = i break return Response(product)
from django.urls import path from . import views urlpatterns = [ path('', views.getRoutes, name="routes"), path('products/', views.getProducts, name="products"), path('prodcucts/<str:pk>/', views.getProduct, name="product"), ]
I already tried int:pk instead of str:pk
You are declaring
products = None and then you iterate with a for loop through
products. That results in iterating over
Try to go for something like this:
from .your_model_module import Product @api_view(['GET']) def getProduct(request, pk): product = Product.objects.get(id=pk) return Response(product)
First you need to import your model. Then you do a
get query within all these Product objects that are stored in your database. The
get query will result in an error (if not found matching object or when multiple objects are found) or will return one object.
If you want to allow that multiple objects are getting found, replace
Also stick to your
At first check whether you need
2 is treated differently in Python.
Then try this:
@api_view(['GET']) def getProduct(request, pk): product = "" for i in products: if i['_id'] == pk: product = i return Response(Product)
The path name
path('prodcucts/<str:pk>/'... seems incorrect kindly check it.