Best way to handle virtual hosts in Django?

Hello everyone and thank you so much for bringing to life this forum!

I was wondering what’s the recommended approach for handling virtual hosts in Django. At the stage I’m in this project, the site framework is a bit overkill. Here’s what I did instead:

def check_domain(request):
    if not request.get_host() == SITE:
        raise PermissionDenied

and then in each view:

def index(request):
    check_domain(request)
    # do stuff

This appoach prevents the user from reaching paths that are not associated with the correct host header. I know it’s a dirty hack, I’m thinking of a custom decorator or a mixin, but I was wondering if there is already some best practice I’m missing.

Thank you!

You can add a middleware that sets request.urlconf to route requests to an entirely different set of URL’s. I’ve used this technique a couple of times quite successfully.

See point #1 in https://docs.djangoproject.com/en/3.0/topics/http/urls/#how-django-processes-a-request

I was thinking about a middleware, but I was missing the link with urlconf. Thank you!

See also for tests: https://docs.djangoproject.com/en/3.0/topics/testing/advanced/#tests-and-multiple-host-names

Yeah I already have a test where the client calls the route with different HTTP_HOST values

Just saw your blog post on the topic. Thanks for covering it!

Sure! I love putting down things on my blog!