开发者

Django | capture sub domain as a string

How do I capture a part of sub-domain name and get that name as a string in my views through a request.

ex:

user.domain.com
developer.domain.com

I want to capture the user part of this domain na开发者_高级运维me through a request (lets say when the first time user hits the page).

Thanks.


This can be done using middleware.

Here is what I have been using...

class SubdomainMiddleware:
    """ Make the subdomain publicly available to classes """

    def process_request(self, request):
        domain_parts = request.get_host().split('.')
        if (len(domain_parts) > 2) or (len(domain_parts) == 2 and domain_parts[1].find('localhost') != -1):
            subdomain = domain_parts[0]

            if (subdomain.lower() == 'www'):
                subdomain = None
            domain = '.'.join(domain_parts[1:])
        else:
            subdomain = None
            domain = request.get_host()

        request.subdomain = subdomain
        request.domain = domain

I got this code from somewhere and modified it a little, although I can't recall where it was originally from.

Just Put that in a file somewhere, then add it to your MIDDLEWARE_CLASSES list in settings.py.

Then, you'll be able to access the subdomain using request.subdomain wherever request is available (e.g. in views, where I assume you will need it)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜