Search code examples
pythondjango-hosts

django-hosts - How to manage invalid urls in a subdomain .django.urls.exceptions.Resolver404?


I have already implemented django-hosts library in my system. When i access a invalid URL in my domain, it will show the 404 page and everything fine. but when i access an invalid URL in my subdomain it raise a 500 error not going or 404.

base.py

ROOT_HOSTCONF = 'core.hosts'
DEFAULT_HOST='default'

hosts.py

from django_hosts import patterns, host
from django.conf import settings

host_patterns = patterns('',
    host(r'', settings.ROOT_URLCONF, name='default'),
    host(r'api', 'api.urls', name='api'),
)

api.urls.py

from django.urls import path
from django.conf import settings
from django.conf.urls import url
from django.urls import path, include
from django.conf.urls.static import static
from .views import *

app_name = 'api'
urlpatterns = [
    url(r'^$', home.as_view(), name="home_api"),
    path('<slug:uid>/<slug:conference_id>', conference.as_view(), name="api_conference"),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns += [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ]
    
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

when i request to http://api.mydomain.com/favicon.ico, it shows

Traceback (most recent call last):
  File "/home/eps64/.local/share/virtualenvs/my-project-aV6d6yYu/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/eps64/.local/share/virtualenvs/my-project-aV6d6yYu/lib/python3.6/site-packages/django/core/handlers/base.py", line 100, in _get_response
    resolver_match = resolver.resolve(request.path_info)
  File "/home/eps64/.local/share/virtualenvs/my-project-aV6d6yYu/lib/python3.6/site-packages/django/urls/resolvers.py", line 558, in resolve
    raise Resolver404({'tried': tried, 'path': new_path})
django.urls.exceptions.Resolver404: {'tried': [[<URLPattern '^$' [name='home_api']>], [<URLPattern '<slug:uid>/<slug:conference_id>' [name='api_conference']>]], 'path': 'favicon.ico'}

how do i handle invalid URL requests in the subdomain?


Solution

  • The official documentation on how to set up custom error views: https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views

    Please put the handler in your api.urls.py