I'm using django-rest-framework (DRF) to have a browsable API which shall be available under the api
subdomain e.g. api.localhost:8000
. To serve subdomains, I'm using django-hosts.
I'm having trouble to achieve login and logout functionality on API level (i.e. under the api
subdomain).
The subdomains work but I can't get the DRF autentication mechanism to work anymore.
Problem
Visiting api.localhost:8000/
shows the browsable api page which is fine. The DRF Log in button is also available. Using this button shows the log-in form, but when submitting the form, I'm redirected to http://login/
which of course can't be resolved and thus the login fails. The same applies to the logout functionality, which leads to http://logout/
and also fails.
Below are screenshots for these steps.
Django Settings
ROOT_URLCONF = "server.urls"
ROOT_HOSTCONF = "server.hosts"
DEFAULT_HOST = "api"
django-hosts configuration
# server/hosts.py
from django_hosts import patterns, host
from django.conf import settings
host_patterns = patterns(
'',
host(r"api", "server.api_urls", name="api"),
host(r"admin", "server.admin_urls", name="admin"),
host("", settings.ROOT_URLCONF), # resolves to server/urls.py
)
URLS configuration
# server/urls.py
from django.urls import include, path
# this is my root url conf
urlpatterns = [
path("", include("server.api_urls")),
path("", include("rest_framework.urls", namespace='rest_framework')),
path("", admin.site.urls),
]
I'm not happy with this, but even though I serve it at another subdomain, without adding path("", admin.site.urls)
to the root urls conf, I always got 'admin' is not a registered namespace
. For the same reason I included rest_framework.urls
here, because otherwise the namespace rest_framework
was not registered.
# server/api_urls.py
urlpatterns = [
path("", include('rest_framework.urls', namespace='rest_framework')),
path("", include("myapp.urls")), # here is the DRF routing
]
In order to use the DRF authentication mechanism and the Log in
and Log out
button, I include the rest_framework.urls
under the namespace I registered before. After that, the usual app urls are included which route the users
API endpoint shown in the screenshot below.
# server/admin_urls.py
from django.contrib import admin
urlpatterns = [
path("", admin.site.urls),
]
Screenshots
Visiting api.localhost:8000/
shows the browsable api page.
Using the Log in
Button redirects to http://api.localhost:8000/login/?next=/
which is fine.
But after submitting the form, I'm redirected to http://login/
which of course can't be resolved and thus the login fails. The same applies to the logout functionality, which leads to http://logout/
and also fails.