Search code examples
djangoajaxdjango-rest-frameworkdjango-urlsdjango-4.0

Django update from 3.2 -> 4.0 and DRF Paths


I wanted to try and upgrade my django app that runs just fine on django 3.2.6 to the next release, but even in testing I came across the deprecated url (https://docs.djangoproject.com/en/4.0/ref/urls/).

So I replaced the last lines in the urls.py:

router = routers.DefaultRouter()
router.register(r'products', views.ProductViewSet, basename = "products")

urlpatterns = [
    ...,
    url('api/', include(router.urls)),
]

to:

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

but on a site that has the url http://127.0.0.1:8003/productspage/ I now get the error message: The current path, productspage/api/products/, didn’t match any of these.

The path for the api in the ajax calls with django 3.26 was working:

async function doAjax ( ) {
    let result = await $.ajax({url: "api/products/"});
}

so I totally see why this would not work - but how (and where?) do I fix it?

I thought about handing an absolute path (like ${window.location.hostname}/api/products/) to ajax, or providing a basename for the template? Can I fix it in Django?


Solution

  • Django url was alias to re_path and not to path so in your case

    ...
    re_path('api/', include(router.urls)),
    ...