Jesús Cota
Jesús Cota

Reputation: 535

Customize CSS from Code (Django)

Im writting an app on django, and want to implement a feature that change the CSS settings. For example, on my settings module i want to change the color of the font, or the size of the font, any idea of how can i implement that?.

Thanks!

Upvotes: 0

Views: 291

Answers (4)

mccc
mccc

Reputation: 2454

I'm using a custom view to return a dynamic CSS file; it uses file caching to avoid rendering over and over for each request.

View function:

@cache_page(None)  # won't expire, ever
def dyn_css(request):
    (css_theme, created) = CSS_Theme.objects.get_or_create(pk=1)
    return render_to_response('dynamic.css', {'theme': css_theme},
                              content_type="text/css")

Reset function, called "manually" when needed:

def reset_cache(request, view='dyn_css', args=None):
    from django.core.cache import cache
    from django.utils.cache import get_cache_key

    if args is None:
        path = reverse(view)
    else:
        path = reverse(view, args=args)

    request.path = path
    key = get_cache_key(request)
    if key in cache:
        cache.delete(key)

CSS file:

.row {
    background-color: {{ theme.background_color }} !important;
}

Upvotes: 1

dylrei
dylrei

Reputation: 1738

There are a few different approaches you can take here.

The easiest is to have static css for classes that you set dynamically.:

<P class='{{ dynamic_classes }}'>

You could also make some CSS overrides in your regular views. For example, if you wanted a to render in red under a "warning" condition:

</head>
<style>
   {% if warning %}
   b {color: red;}
   {% endif %}
</style>

It is also possible to render your CSS as a dynamic view instead of static, but I'd explore both of these other options first.

Upvotes: 1

eliteware
eliteware

Reputation: 144

You should check http://sass-lang.com/ It allows you to set variables such as colors and sizes, then use theme across your website or app, and when you need to change something all you have to do is change the variable.

Upvotes: 0

soulprovidr
soulprovidr

Reputation: 754

The simplest way would be to create a variable in your settings.py file called FONT_COLOR (for example).

Then, when you are rendering a template, you could add FONT_COLOR to the response context and use it to override your CSS.

template.html

...

<style>
    body {
        color: {{ FONT_COLOR }};
    }
</style>

...

Upvotes: 1

Related Questions