i am facing issue to add path to product urls.py file ,i dont know how

111 Views Asked by At
```

I am creating CRUD for categories I make a CategoriesViewSet. on the other hand, I register the router as default in urls.py(Products) for viewset of categories but I don't know how to add a path into the product => urls.py and also the path I want to include into the core url.py file.


 
    
    product => urls.py
    
    router =routers.DefaultRouter()
    router.register(r'categories', CategoryViewSet)
    
    urlpatterns = [
        
        path('list/',ProductList.as_view(),name="View Product"),
        path('add/',AddProduct.as_view(),name="Create Product"),
        path('<int:pk>/',ProductDetails.as_view(),name="product_detail"),
        # path('categories/', CategoryViewSet.as_view({'get':'list'}))
        path(r'^', include(router.urls)),
        re_path(r'categories/', CategoryViewSet.as_view({'get':'list'}), 
            name='product-detail')
    
    ]
    
    
    Core => urls.py
    
        path('admin/', admin.site.urls),
        path('api/product/', include('products.urls')),
        path('api/user/', include('user.urls')),
        
    
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
    urlpatterns = format_suffix_patterns(urlpatterns)

2

There are 2 best solutions below

0
On

I don't think you have a clear idea of what Routers do in Django.

From DRF's official documentation:

Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests.

REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.

This line:

router.register(r'categories', CategoryViewSet)

according to Django REST Framework's (DRF) documentation, generates 2 URL patterns:

categories/ - Return the list of categories
categories/{pk}/ - Return category with specified primary key (pk)

You don't need to add those again in Product's urls.py. You can either only specify the router.register(...) method, or manually add them like that:

path('categories/', CategoryViewSet.as_view(), name='product-detail')
0
On

It works. In my view I implemented and it works that's why I am asking First of all we have to add the import [re_path and include] in the Urls.py (Products) then we have to add-------------------- ~the code will be added in the urls.py(Products) below the import library.

router = routers.SimpleRouter()
router.register(r'', CategoryViewSet, 'categories')   

in Url Patterns~

re_path(r'^categories/',include((router.urls,'categories'),namespace='categories'))
          

it works.