Search code examples
djangopython-2.7django-templatesdjango-urlswhite-labelling

What is the common practice for white labeling a Django site?


I have a web application that I would like to allow white labeling for our clients. I have done this in PHP/ZendFramework, keying off the hostname (http://example.com), pulling the logo/colors/other from the database and rendering the main layout with those settings.

I am new to Python/Django1.5 and was wondering if anyone has implemented a white label feature into their application. How did you do it? Is there a common practice?

I have done some Googling and found an older blog implementing a white label feature using a url prefix, but I'm still running into some problems with rending the layouts

http://chase-seibert.github.com/blog/2011/08/05/django-white-label-styling-with-url-prefixes.html

Any help would be great! Thanks


Solution

  • I did not find a good answer on this so i just implemented my own solution.

    What I did was create a Whitelabel model that looked like this:

    class Whitelabel(models.Model):
        name = models.CharField(max_length=255, null=False)
        logo = models.CharField(max_length=255, null=True, blank=True)
        primary_domain = models.CharField(max_length=256, null=False) 
    

    Then I created a context processor in application_name/context_processors.py that checks the current host domain and sees if it matches any records primary_domain field. If there is a match, return the values for name and logo and assign them to the parameters SITE_NAME and SITE_LOGO. If no match is found, assign defualt values for SITE_NAME and SITE_LOGO, probably your default application name.

    def whitelabel_processor(request):
        current_domain = request.get_host() 
        whitelabel = Whitelabel.objects.filter(primary_domain=current_domain).order_by('id')
    
        if whitelabel.count() != 0:
            config = {
                'SITE_NAME': whitelabel[0].name, 
                'SITE_LOGO': whitelabel[0].logo, 
                'SITE_DOMAIN': whitelabel[0].primary_domain
                }
        else:
            config = {
                'SITE_NAME': 'MY SITE', 
                'SITE_LOGO': '/static/images/logo.png', 
                'SITE_DOMAIN': 'http://%s' % Site.objects.get_current().domain
                }
    
        return config
    

    Then I added the context processor to my settings file under TEMPLATE_CONTEXT_PROCESSORS

    TEMPLATE_CONTEXT_PROCESSORS = (
        "django.contrib.auth.context_processors.auth",
        ...
        "context_processors.whitelabel_processor",
    

    )

    So that I can call them like so in my base.html template

    <body>
        <h1>{{SITE_NAME}}</h1>
        <img src="{{SITE_LOGO}}" />
    </body>
    

    Here is some more documentation around template context processors. https://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors