Home > Software design >  Change Django theme based on logged in, profile, or toggle
Change Django theme based on logged in, profile, or toggle

Time:11-13

I would like to allow the user to have the ability to change the theme based on the following factors:

  • Anonymous
    • Check localStorage and if empty use default else use localStorage
  • Authenticated
    • Check localStorage and if empty use user profile setting

I have it all working except for Authenticated users, I don't know how to check localStorage.

{% if user.is_authenticated %}
<body >
// How can I check localStorage.getItem('theme') and if null use {{user.profile.theme}}

{% else %}
<body>
  <script>
    var theme = localStorage.getItem('theme')
    if(theme == 'light'){
      document.body.classList.add("theme-light")
    } else if (theme == 'dark'){
      document.body.classList.add("theme-dark")
    } else {
      document.body.classList.add("theme-light")
    }
  </script>
{% endif %}

CodePudding user response:

Here is updated code

<body>
</body>
<script>
var user_theme;
const body = document.body;
var theme = localStorage.getItem('theme') 

// check if user is authenticated & it have theme
{% if user.is_authenticated %}
  user_theme = "{{user.profile.theme}}";
{% endif %}

if(theme){
    if(theme == 'light'){
        body.classList.add("theme-light");
    } else if (theme == 'dark'){
        body.classList.add("theme-dark");
    } else {
        body.classList.add("theme-light");
    }
}else if(user_theme){
    body.classList.add(user_theme);
}
</script>

above code will add localstorage theme first if it exists else it will add authenticated user theme if user is authenticated

  • Related