Currently, I import url configurations into my Django project with:
from django.conf.urls import include
from django.contrib import admin
from django.urls import path, re_path
from rest_framework import routers
from greeter.views import GreeterViewSet
ROUTER = routers.DefaultRouter()
ROUTER.register(r'greeters', GreeterViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^', include(ROUTER.urls)),
]
Is there a way where I can move these parts of the code:
ROUTER = routers.DefaultRouter()
ROUTER.register(r'greeters', GreeterViewSet)
into a separate file in greeter/urls.py
?
And still keep these URLs:
I have tried:
my_project/urls.py
from django.conf.urls import include
from django.contrib import admin
from django.urls import path, re_path
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^greeters/', include('greeter.urls')),
]
greeter/urls.py
from django.conf.urls import url, include
from rest_framework import routers
from .views import GreeterViewSet
ROUTER = routers.DefaultRouter()
ROUTER.register(r'^', GreeterViewSet)
urlpatterns = [
url(r'^', include(ROUTER.urls)),
]
But got:
$ curl -H 'Accept: application/vnd.api+json; indent=2' -X POST http://localhost:8000/greeters/
{
"errors": [
{
"detail": "Method \"POST\" not allowed.",
"source": {
"pointer": "/data"
},
"status": "405"
}
]
}
In case it helps, here is my original question that has been resolved: Method "POST" not allowed with Django Rest Framework
Update:
With the help of the answers, I was able to arrive at this solution:
my_project/urls.py
from django.conf.urls import include
from django.contrib import admin
from django.urls import re_path
urlpatterns = [
re_path('admin/', admin.site.urls),
re_path('greeters/', include('greeter.urls')),
]
greeter/urls.py
from django.conf.urls import include
from django.urls import re_path
from rest_framework import routers
from .views import GreeterViewSet
ROUTER = routers.DefaultRouter()
ROUTER.register(r'', GreeterViewSet)
urlpatterns = [
re_path(r'', include(ROUTER.urls)),
]
With this:
I think this is as good as I can get it. Thanks again for all of the help :)
As I said to you before, the Router needs a prefix. You need to remove that prefix from your main URLs and use it in the router itself.
main:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('greeter.urls')),
]
app:
ROUTER = routers.DefaultRouter()
ROUTER.register(r'^greeter/', GreeterViewSet)
urlpatterns = ROUTER.urls
(Since you don't have any URLs other than the router ones, you don't need to use include there, you can just use the router urls directly.)
Also note, this whole thing is almost certainly not what you want to do; it means you can never have any URLs other than those for your viewset.