Fork me on GitHub

Subdomains in Django: An Example

This post has been updated at 09/07/2011.

In Django Middleware is a class which respond to one of these methods: process_request, process_view, process_response or process_exception. For more informations see the Django middleware docs.

Writing the middleware

In Django Middleware is a class which respond to one of these methods: process_request, process_view, process_response or process_exception. For more informations see the Django middleware docs.

What we need is just use blog/urls.py on blog subdomain instead of main urls.py. It's easy, we just need to rewrite settings.ROOT_URLCONF to proper file:

from django.conf import settings
import re

class SubdomainsMiddleware:
    def process_request(self, request):
        request.domain = request.META['HTTP_HOST']
        request.subdomain = ''
        parts = request.domain.split('.')

        # blog.101ideas.cz or blog.localhost:8000
        if len(parts) == 3 or (re.match("^localhost", parts[-1]) and len(parts) == 2):
            request.subdomain = parts[0]
            request.domain = '.'.join(parts[1:])

        # set the right urlconf
        if request.subdomain == 'blog':
            settings.ROOT_URLCONF = 'blog.urls'
        else:
            settings.ROOT_URLCONF = 'web.urls'

We have also added domain and subdomain properties to the request object, so we can access to these variables in your views.

Get it working

DNS

First you should ensure that all the subdomains are routed to server where your application runs. It should look like this:

* CNAME 101ideas.cz

Apache

ServerAlias blog.101ideas.cz

Of course if you like to route all the subdomains to your application, then use the wilcard. For example ServerAlias *.101ideas.cz.

Django

We need to register the middleware in settings.py:

import middleware

MIDDLEWARE_CLASSES = ('middleware.SubdomainsMiddleware',)

Localhost settings for development

First you must add this line to your /etc/hosts:

127.0.0.1 blog.localhost

It should works immediately. Just start ./manage.py runserver and try to go to http://blog.localhost:8000/.

Cookies

If you want to share cookies you have to set cookie domain to .yourdomain.com, otherwise it will default to blog.yourdomain.com, so it won't be shared:

SESSION_COOKIE_DOMAIN = '.seenreport.com' if not DEBUG else '.localhost'

And that's it! Enjoy Django!

blog comments powered by Disqus
About

RSS

All Posts IT Python Django

Tags

GitHub projects

Twitter @botanicus

Recent Comments