Home > Software design >  How to get rid of app name in the particular url?
How to get rid of app name in the particular url?

Time:08-02

I have this urls.py in my app

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from products import views


app_name = 'products'
router = DefaultRouter()
router.register(r'products', views.ProductViewSet, basename='products')
router.register(r'categories', views.ProductCategoryViewSet, basename='categories')
router.register(r'brands', views.BrandViewSet, basename='brands')

urlpatterns = [
    path('', include(router.urls)),
]

And this is my project's urls.py

from django.contrib.auth import views as auth_views
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'),
         name='login'),
    path('logout/', auth_views.LoginView.as_view(template_name='users/logout.html'),
         name='logout'),
    path('__debug__/', include('debug_toolbar.urls')),
]

urlpatterns  = [
    ...
    path('products/', include('products.urls', namespace='products')),
    ...
]

And viewsets:

from rest_framework import viewsets, permissions
from .models import (
    Product,
    ProductCategory,
    Brand,
)
from .serializers import ProductSerializer, ProductCategorySerializer, BrandSerializer

#all other viewsets are the same
class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

A router for my app generates urls almost as expected, I can go to 'site/products/categories' for categories 'site/products/brands' for brands BUT for products url is 'site/products/products'. How to make it not to add app name in this case? I want it to be just 'site/products'.

CodePudding user response:

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from products import views


app_name = 'products'
router = DefaultRouter()
router.register(r'categories', views.ProductCategoryViewSet, basename='categories')
router.register(r'brands', views.BrandViewSet, basename='brands')
router.register(r'', views.ProductViewSet, basename='products')

urlpatterns = [
    path('', include(router.urls)),
]

Django is trying to match url to one url from list of router urls, so if you have two same urls, but one is faster in list, Django will pick always the first one.

  • Related