How to grab a subdomain in a Django url pattern?

I have a Django application that currently supports multiple languages. I would like to add support for subdomains so that “de.mysite.com” requests for German items and mysite.com in English (the default language). There will be about 20 subdomains pointing to the same Django application.

I have an abstract model with all fields for my data and a derived model for each language. Each language has its own database table, for example:

class ArticleBase(models.Model):
    title = models.CharField(max_length=240, unique=True)
    date_added = models.DateField(auto_now_add=True)

    class Meta:
        abstract = True

# This is English, the default.
class Article(ArticleBase):
    pass

class Article_de(ArticleBase):
    pass

I can get articles like this (today it works for me):

def article(request, title, language=None):
    if language:
        mod = get_model('app', 'Article_' + language)
        items = mod.filter(title=title)
    else:
        items = Article.objects.filter(title=title)

This is my current URL pattern:

url(r'^article/(?P<title>[a-zA-Z_-]+)/$", 'app.views.article', name='article'),

URL-, ? , ?

+4
3

URL- django URL-, . , .

, , , , , ( accept-language django )

localemiddleware , / .

, : /? ? 20 , 1 .

UPDATE:

, ( ):

class SubDomainLanguage(object):
    def process_request(self, request):
        try:
            request.session['django_language'] = request.META['HTTP_HOST'].split('.')[0]
        except KeyError:
            pass

, , :

MIDDLEWARE_CLASSES = (
    ...
    'django.contrib.sessions.middleware.SessionMiddleware',
    'subdomainmiddleware.SubDomainLanguage',
    'django.middleware.locale.LocaleMiddleware',
    ...
)

, i18n Django.

request.LANGUAGE_CODE

+5

, , 1.2.3.mydomain.net. local_settings.py :

DOMAIN = 'EXAMPLE.net'
TEST_SUBDOMAINS = ["127.0.0.1", "localhost", "testserver"]

, , . :

if (DOMAIN in TEST_SUBDOMAINS):
    return HttpResponse("test only")
subdomain = request.META['HTTP_HOST'].replace((DOMAIN), "")[:-1] 
# -1 is to remove the trailing "." from the subdomain
if subdomain and subdomain != "www" :
# whatever you need...
0

You can simply use this easy-to-use django-subdomains library . It also supports URL routing and subdomain reversal.

0
source

All Articles