1

Is it possible to make part of a page use a totally different CSS file when the user chooses a different option in a select box using Django?

What I'm basically trying to do is add a theme selector to the page.

Thanks.

bodger
  • 1,112
  • 6
  • 24

2 Answers2

2

To create a theme selector in Django use a form to get the stylesheet choice from the user and store the style choice in a session. The valid form should execute:

request.session['style'] = the_style_choice

https://docs.djangoproject.com/en/1.5/topics/http/sessions/

Use a context processor to return the right stylesheet each request in settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "MyContextProcessor.get_style", 
)

In MyContextProcessor.py

def get_style(request):
    if 'style' in request.session:
        style = request.session.get('style')                
    else:
        style = 'some_style.css'
        request.session['style'] = style
    return {'style': style, }

https://docs.djangoproject.com/en/1.5/ref/templates/api/#subclassing-context-requestcontext

In your base template add the style:

{{ style }}

You can use Ajax in the form to give the user a smooth experience: https://docs.djangoproject.com/en/1.5/topics/class-based-views/generic-editing/#ajax-example

allcaps
  • 10,945
  • 1
  • 33
  • 54
  • @bodger: Did my answer help you? Feedback is appreciated. – allcaps Aug 03 '13 at 10:12
  • This is very clever, brilliant solution. Personally I will be using this in conjunction with django sites and be storing this in a 1-1 relationship with site_id. – Derek Adair Feb 18 '17 at 17:15
-1

This should be done with javascript, not Django. Look into doing it with Jquery.

Edit: How do I switch my CSS stylesheet using jQuery?

Community
  • 1
  • 1
  • I disagree with this; It is fine to do this in django. 1)Graceful degredation 2) using sessions to store themes loses the ability to configure and store a theme for an individual site – Derek Adair Feb 18 '17 at 18:11
  • Also on mobile or slow internet users visiting a page that is not cached would have a rather jarring experience; they will see the default theme flash then change to the styles loaded by js – Derek Adair Feb 18 '17 at 18:15