Django REST Framework: how to add prefix to version control URL

I am trying to create a version for a REST application. Here is my url

www.myapi.com/foo [default version] www.myapi.com/v1/foo [version one] 

This is the project structure.

 ├── __init__.py ├── settings.py ├── urls.py ├── default_app │ ├── __init__.py │ ├── serializer.py │ ├── models.py │ ├── views.py │ ├── urls.py │ └── v1_app ├── __init__.py ├── serializer.py ├── models.py ├── views.py ├── urls.py 

default_app urls.py

 from django.conf.urls import * from default_app import views as df_views from rest_framework import routers router = routers.DefaultRouter() router.register(r'foo', df_views.viewname, "foo") urlpatterns = router.urls 

v1_app urls.py

 from django.conf.urls import * from v1_app import views as ver_views from rest_framework import routers router = routers.DefaultRouter() router.register(r'foo', ver_views.viewname, "foo") urlpatterns = router.urls 

main file for urls.py

 from django.conf.urls import patterns, include, url from defualt_app import urls as default_urls from v1_app import urls as v1_urls from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += patterns('', url(r'^', include(default_urls, namespace="default")), url(r'^v1/', include(v1_urls, namespace="v1")) ) urlpatterns += staticfiles_urlpatterns() 

My problem is that when I use a simple URL without a prefix, it works

www.myapi.com/foo

and when I used the prefix version v1 or v2, it gives an error [Page not found (404)]

www.myapi.com/v1/foo

I got this idea from this link https://stackoverflow.com/a/464626/

If I do not use the middleware class, is it possible to get the same result?

thanks

+5
source share
1 answer

The Django REST Framework does not well support URL namespaces , but there are solutions that allow them to work in most cases.

In the case of serializers, you must define all the fields that are linked by the hyperlink to the HyperlinkedRelatedField , including the url field, which is automatically added, which is HyperlinkedIdentityField . This includes setting the view_name argument in all fields to the correct, automatically generated view name. It should be something like [namespace]:[base_name]-detail .

But it also means you cannot use the DefaultRouter index page , which is generated by DefaultRouter , since it does not process namespaces at all. To get one of them, you will need to either create your own or override the automatically created view in the router.

0
source

Source: https://habr.com/ru/post/1206246/


All Articles