1

I have a website running Django whose main domain is example.com. What I want to achieve is to behave in a different way when an user access from example2.com (specifically loading custom CSS).

I understand that I have to make some changes to the web server and that is not a problem. My question is focused on how to accomplish this with Django.

There is something called Django sites that could be useful for this, but I am not sure if this is an overkilling feature for such a "simple" thing. However I am aware that multiple changes would be needed (paths, cookies domain, etc), so... is this the recommended way to do it?

Bob Dem
  • 991
  • 1
  • 11
  • 23

1 Answers1

1

It's a pretty simple thing to accomplish. You have a few different options.

Checking the HTTP_HOST straight from a template

A very simple approach would be from a template to check the request.META dictionary's value for the HTTP_HOST key.

{# Anything other than port 80, HTTP_HOST will also include the port number as well #}
{% ifequal request.META.HTTP_HOST 'example2.com' %}
    <!-- your css imports here -->
{% endifequal %}

Remember, this is set by the client though, so if you were doing anything else that was security-sensitive, this would NOT be the approach to use. Just for loading some CSS though, it would be fine.

Custom middleware

Another option would be to create custom middleware and check this same object from there. Basically the same process but you'd probably want to do something like set an extra key on the request object

In some file.. yourproject/someapp/middlware.py

class DomainCheckMiddleware(object):
    def process_request(self, request):
        if request.META['HTTP_HOST'] == "example2.com":
            request.IS_EXAMPLE2 = True
        else:
            request.IS_EXAMPLE2 = False
        return None

In your settings.py

MIDDLEWARE_CLASSES = ( 
    # whatever middleware you're already loading
    # note: your middleware MUST exist in a package that's part of the INSTALLED_APPS
    'yourproject.someapp.DomainCheckMiddleware' 
)

In your template

{% if request.IS_EXAMPLE2 %}
    <!-- load your css here -->
{% endif %}

This is more legwork, and pretty much does the same thing, but you could easily apply some extra tests to see if you're in debug mode or just accessing over localhost:8000 and still set IS_EXAMPLE2 to true, without making your templates more difficult to read.

This also has the same downfall mentioned previously.

https://docs.djangoproject.com/en/dev/topics/http/middleware/

Using the sites framework

Using the sites framework is only valid if you have enabled it (django.contrib.sites) enabled, which it no longer is by default and is overkill for your purposes. You can see an example of how that would work from this answer though: How can I get the domain name of my site within a Django template?

Community
  • 1
  • 1
Derek Curtis
  • 639
  • 6
  • 14