Getting a 404 on defined urls in django rest framework
I'm trying to access urls defined in django app (abcd).
apps:
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
'rest_framework',
"abcd",
]
urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls), path('', include('abcd.urls'))
]
abcd.urls
from rest_framework import routers
from abcd import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet, 'users')
router.register(r'groups', views.GroupViewSet, 'groups')
urlpatterns = router.urls
views.py
from rest_framework.viewsets import ViewSet
class UserViewSet(ViewSet):
pass
class GroupViewSet(ViewSet):
pass
Whenever I try accessing: http://localhost:8000/users or http://localhost:8000/groups, I get a 404.
You need to define urlpatterns inside of abcd.urls for the path endpoint /users and /groups should be like this.
abcd/urls.py
from rest_framework import routers
from django.urls import path, include
from abcd import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet, 'users')
router.register(r'groups', views.GroupViewSet, 'groups')
urlpatterns = [
path('', include(router.urls)),
]
Need to migrate new module to make it readable by django. Can use this
python manage.py makemigrations abcdpython manage.py migrate
I will admit that the docs are indeed misleading [django-rest-framework.org] on this topic but here is my recommendation:
If you do not need a basename, don’t use it.
Change your code to this and it will work:
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
The DefaultRouter generates routes for a ViewSet according to the available methods on the ViewSet. A ViewSet class does not provide any method handlers such as .get() or .post(), but instead provides actions such as .list() and .create(). See the full mapping here. [django-rest-framework.org]
Since your ViewSet does not have any methods, a get request will return a 404 status code with status text —Not Found.