DRF Browsable API only shows one Router - django

Essentially, depending on the order in which I add my routes to my urlpatterns the browsable API will only show one router at a time. Here's my code:
urls.py:
from django.conf.urls import url, include
from rest_framework import routers
from .views import PlantViewSet
# url router
router = routers.DefaultRouter()
router.register(r'plants', PlantViewSet, base_name='Plants')
djoser_urls = [url(r'^', include('djoser.urls')), ]
urlpatterns = [
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^docs/', include('rest_framework_swagger.urls')),
# url(r'^', include(router.urls)),
# url(r'^', include('djoser.urls')),
] + djoser_urls + router.urls
This only displays the djoser urls:
However simply reversing the order in which I add the urls:
urls.py:
from django.conf.urls import url, include
from rest_framework import routers
from .views import PlantViewSet
# url router
router = routers.DefaultRouter()
router.register(r'plants', PlantViewSet, base_name='Plants')
djoser_urls = [url(r'^', include('djoser.urls')), ]
urlpatterns = [
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^docs/', include('rest_framework_swagger.urls')),
# url(r'^', include(router.urls)),
# url(r'^', include('djoser.urls')),
] + router.urls + djoser_urls
This only displays the router urls!
The same thing happens when I just use the include() lines I've commented out, whichever comes first in the list is the only router that gets displayed. Furthermore, no matter which router gets picked up the api-auth/ and docs/ urls are never shown. Is there anyway to get a unified api root without having to create my own custom view?

This doesn't have anything to do with Django REST framework, it happens because of how Django deals with duplicate urls.
You are trying to have a single url be handled by two different views: The DRF router index and the djoser root view. Django will only display the first view matching the search pattern that it finds, which is generally the first urls that are included in the url patterns.
Django REST framework will also not detect multiple routers that are available and group them together on the same page, which is sounds like you are hoping to see. Even if it could, djoser doesn't use a router so there is no way that DRF could actually know to include it.
Is there anyway to get a unified api root without having to create my own custom view?
So to answer the main question: No it is not possible for Django REST framework to automatically group these views together. You are going to need to create your own customer view to handle this.

Related

Django Rest Framework: incorrect hyperlink on second viewset of same model

I'm trying to provide two distinct APIs using DRF but I'm unable to get the second app to stop creating
hyperlinked references based on the first. It's essentially the same problem as Django Rest Framework with multiple Viewsets and Routers for the same object but I'm unable to get it working.
app1/urls.py:
router = SimpleRouter(trailing_slash=False)
router.register(prefix=r'article', viewset=app1.ArticleViewSet, basename=r'article')
urlpatterns = [path(f'', include(router.urls)]
app2/urls.py:
router = SimpleRouter(trailing_slash=False)
router.register(prefix=r'published', viewset=app2.ArticleViewSet, basename=r'published')
urlpatterns = [path(f'', include(router.urls)]
site/urls.py:
urlpatterns = [
path('app1/', include('app1.urls')),
path('app2/', include('app2.urls')),
]
While both viewsets are of the same model, the queryset & serializer for each is different.
When I GET an item from /app2/published, it has an app1 URL:
"url": "http://localhost:8000/app1/article/5461"
What I'm wanting is for items retrieved via app2 to have:
"url": "http://localhost:8000/app2/published/5461"
From looking at the docs, it appears that providing basename should do what I want, but I'm not having any luck with getting it to work.
Try the following code in your site/urls.py:
from app1.urls import router as app1_router
from app2.urls import router as app2_router
router = routers.DefaultRouter()
router.registry.extend(app1_router.registry)
router.registry.extend(app2_router.registry)
urlpatterns = [
path('', include(router.urls)), # default page to show api
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
You can see an example here, which has same structure as you need.

How to fix "error path not found" in django rest framework

I am trying to build an API of my blogging website using Django rest framework, but my URL is not matching.
I am trying Django Rest framework for the first time so I am not quite able to fix this. But I think I mess this up in url_patterns.
Here is my URL code from the main directory(the directory which contains settings.py) .
`
from django.conf.urls import url,include
from django.contrib import admin
from django.urls import path, include
from blog import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'apipost',views.PostViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('blog.urls')),
path('api-auth/',include('rest_framework.urls',namespace='rest_framework')),
]
`
I am trying url http://127.0.0.1:8000/apipost and expect to get value in json format.
You need to add router.urls to your urlpatterns.
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('blog.urls')),
path('api-auth/',include('rest_framework.urls',namespace='rest_framework')),
]
urlpatterns += router.urls
Django REST Framework Won't magically register your router in urlpatterns, you have to do it by yourself. You can use urlpatterns += router.urls if you want to add them to the root of your urlpatterns, or url(r'^api/', include((router.urls, 'app_name'))), if you want to set subpath for them.

Not able to add url in Django router

I am not able to add workers URL which is pointing to a method in views.py. In below urls.py configuration, I had created a DefaultRouter, and registered 6 URLs. First 5 are working good(They are Class Based Views), however the last URL(workers, which is method based view) is not working. This URL is not matched with any of the URLs listed in url.conf. Error message I am getting 'Using the URLconf defined in maidFactory.urls, Django tried these URL patterns, in this order:. . . . . . .The current URL, workers/, didn't match any of these.'
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'slots', views.SlotViewSet)
router.register(r'city', views.CityViewSet)
router.register(r'location',views.LocationViewSet,base_name='locationMy')
router.register(r'workers',views.WorkerViewSet,base_name='getWorkersBySlotAndLocation')
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
#url(r'^', include('maidFactory.api.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^auth/', include('rest_framework_social_oauth2.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))]
My method based view is as follows:
def WorkerViewSet(request):
cursor = connection.cursor()
#cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
cursor.execute("select p.wid,p.fname, a.description from workerProfile as p, workerAccount as a where a.isactive=1 and a.wid=p.wid")
row = cursor.fetchone()
return HttpResponse(row)
Your WorkerViewSet is not a actual DRF ViewSet but a Django function-based view returning Django HttpResponse.
You should convert it to a proper DRF viewset and then register your router with this viewset.
Another option is to add this as a url in urlpatterns in your urls file and it should work perfectly.
urlpatterns = [
url(r'^my/url/path/$', my_views.WorkerViewSet), # This will work
....
]

404 error in django rest framework

When I am hitting http://127.0.0.1:8000/segment_address but I am getting 404 error:
This is my urls.py
from addFixAPI import views
router = routers.DefaultRouter()
router.register(r'segment_address', views.search_addresses,base_name='segment_address')
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^locality/', include('locality.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^django-rq/', include('django_rq.urls')),
)
First you should check that "app" has registered its "urls" in the main "urls" project.
It is obvious but I dont see that you include the line
from django.conf.urls import url, include
from rest_framework import routers
make sure you register long URLs first. ie: segment_address/things/pk/ must be registered before segment_address/
You have to register your ViewSet class. I see a snake_case name in your register(), which implies you are either not following PEP 8, or you are not registering a class that extends a viewset.
See here for examples:
https://www.django-rest-framework.org/api-guide/generic-views/
And just in case anyone finds it useful: You don't use .as_view() when registering in the router. You only need .as_view() if you are registering using the url() method.

Registering API in apps

With django-rest-framework I'm using the DefaultRouter
I want to provide APIs to several apps, so my question is can I do this in a django manner and put my router registrations in each app URLconf and have them appear either as one aggregate api or ideally in a namespaced way.
In other words if app1 contains modelA and modelB, while app2 contains modelC:
can I declare 2 routers that appear at mysite/app1/api and mysite/app2/api, or
can I have a single api at mysite/api which lists all three models yet register the individual models in their own app's urls.py
Something like
router = DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(include('app1.apis')
router.register(include('app2.apis')
Alternatively is there a simple way in which my router variable can be made available in each app's URLconf so that they can call router.register? I'm not sure if
urlpatterns = patterns('',
url(r'^snippets/', include('snippets.urls', namespace="snippets"))
...
url(r'^api/', include(router.urls)),
actually cause the code in app1/urls.py to be executed at that point so that it could call router.register somehow, so that the final url call includes all the app registrations as well as the project one.
UPDATE
Using a variation on Nicolas Cortot's option 2 I get my specific resource API to work, but it is not listed as an available resource in the root API at myserver\api\
I assume that somehow DefaultRouter creates it's own page definition and router.register adds entries to it. My current setup (and I think Nicholas's option 1 as well) create two separate routers, and only one can get displayed as the server root, with the setup below, myserver\api\ lists users but not snippets.
Here's my current setup:
project urls.py:
router = DefaultRouter()
router.register(r'users', views.UserViewSet)
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(router.urls)),
url(r'^api/', include('snippets.apiurls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
)
project/snippets/apiurls.py:
router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet)
urlpatterns = patterns('',
url(r'^', include(router.urls)),
)
If I reverse the order of the entries in the project urls.py as:
url(r'^api/', include('snippets.apiurls')),
url(r'^api/', include(router.urls)),
then I get snippets listed but not users
I guess Django is serving the first matching route.
Unless someone can tell me otherwise I seem to need a single router variable to be passed around and added to somehow.
To get all apps in the same API root, you need to register all your apps with the same DefaultRouter.
One way to achieve this is to make a custom router, which intercepts the register call and propagates it to a shared router. You then use this shared router to get the api urls.
class SharedAPIRootRouter(SimpleRouter):
shared_router = DefaultRouter()
def register(self, *args, **kwargs):
self.shared_router.register(*args, **kwargs)
super().register(*args, **kwargs)
# if not py3: super(SharedAPIRootRouter, self).register(*args,**kwargs)
Then in each app:
# in app1/urls.py
router = SharedAPIRootRouter()
router.register(r'app1', App1ModelViewSet)
# in app2/urls.py
router = SharedAPIRootRouter()
router.register(r'app2', App2ModelViewSet)
In your main urls.py, you must ensure you import the app urls so that registration occurs before we ask for shared_router.urls
import app1.urls
import app2.urls
def api_urls():
return SharedAPIRootRouter.shared_router.urls
urlpatterns = patterns(
'',
url(r'^api/', include(api_urls())),
)
if you do not want to import the urls explicitly, you can do it by convention:
def api_urls():
from importlib import import_module
for app in settings.INSTALLED_APPS:
try:
import_module(app + '.urls')
except (ImportError, AttributeError):
pass
return SharedAPIRootRouter.shared_router.urls
This is possible by passing around a single router instance as follows.
Create a file called router.py or similar in your main project folder:
from rest_framework import routers
common_router = routers.DefaultRouter()
In each app's urls.py put:
from main.router import common_router as router
router.register(r'myapp-model-name', MyAppViewSet)
In your main urls.py put:
import my_app1.urls # to register urls with router
import my_app2.urls # to register urls with router
...
# finally import router that includes all routes
from main.router import common_router
urlpatterns = [
...
url(r'^api/', include(common_router.urls)),
...
]
Both options are possible. You can either expose the router or the urls in each app, and merge those into your global urls. I usually prefer using urls (option 2) because it gives more flexibility in each app: you can define extra non-api URLs as needed.
Option 1
In your global urls.py:
from app1.api.routers import router1
from app2.api.routers import router2
urlpatterns = patterns('',
url(r'^snippets/', include('snippets.urls', namespace="snippets"))
...
url(r'^app1/api/', include(router1.urls)),
url(r'^app2/api/', include(router2.urls)),
)
You can as easily use the same endpoint for both routers (as long as you're careful not to use conflicting routes):
urlpatterns = patterns('',
url(r'^snippets/', include('snippets.urls', namespace="snippets"))
...
url(r'^api/', include(router1.urls)),
url(r'^api/', include(router2.urls)),
)
Option 2
In appN/api/urls.py:
router = DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(include('app1.apis')
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^misc/', some_other_view),
)
In your global urls.py:
urlpatterns = patterns('',
url(r'^snippets/', include('snippets.urls', namespace="snippets"))
...
url(r'^api/', include('app1.api.urls')),
url(r'^api/', include('app2.api.urls')),
)
Note that the urls modules do not need to be the same as the urls for standard views.
As a more advanced variant on #Grischa, I like to extend his approach:
In the main's routers.py:
from rest_framework import routers
api_v1_router = routers.SimpleRouter()
In the main's urls.py:
from django.urls import include, path
import app1.urls
from .routers import api_v1_router
# Register app urls
app1.urls.register(api_v1_router)
app2.urls.register(api_v1_router)
...
urlpatterns = [
...
path('v1/', include((api_v1_router.urls, 'v1'))),
...
]
In each app's urls.py:
from main.routers import api_v1_router
from .apis import MyAppViewSet1, MyAppViewSet2
def register(router):
router.register(r'myapp-model-name1', MyAppViewSet1)
router.register(r'myapp-model-name2', MyAppViewSet2)
Two advantages of this approach:
You can control the registration of the apps in the main urls.py
The flexibility of register(router) allows you to register to different routers, for example when using both v1 and v2 for versioning.