from django.db import models
class City(models.Mode):
title = models.CharField(max_length=50)
subdomain = models.CharField(max_length=10)
class SubdomainMiddleware(MiddlewareMixin):
DEFAULT_SUBDOMAIN = 'msk'
def process_request(self, request):
subdomain, _ = self.split_subdomain(request.META['HTTP_HOST'])
if subdomain:
request.city = get_object_or_404(City, subdomain=subdomain)
else:
request.city = City.objects.get(subdomain=self.DEFAULT_SUBDOMAIN)
def split_subdomain(self, host):
host = request.META['HTTP_HOST']
if '127.0.0.1' in host:
return None, host.split('.')
bits = host.split('.')
if len(bits) <= 2:
sub, other = None, bits
else:
sub, other = bits[0], bits[1:]
if sub in escape:
other = [sub] + other
sub = None
return sub, other