Alter Django theme according to user login status, profile settings, or activation of a toggle switch

I'm looking to give users the option to change the theme based on specific criteria:

  • For Anonymous Users:
    • Check localStorage and use default if empty, otherwise use localStorage value
  • For Authenticated Users:
    • Check localStorage and use user profile setting if empty

Everything is working well for Anonymous users, but I'm unsure how to handle it for Authenticated users when checking localStorage.

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

{% 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 %}

Answer №1

Check out the latest version of this code snippet:

<header>
</header>
<script>
var user_style;
const page = document.head;
var style = localStorage.getItem('style') 

// Validate user authentication and retrieve custom theme
{% if user.is_authenticated %}
  user_style = "{{user.profile.style}}";
{% endif %}

if(style){
    if(style == 'light'){
        page.classList.add("style-light");
    } else if (style == 'dark'){
        page.classList.add("style-dark");
    } else {
        page.classList.add("style-default");
    }
}else if(user_style){
    page.classList.add(user_style);
}
</script>

This updated code prioritizes the local storage style first, followed by the authenticated user's custom style if the user is indeed authenticated.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: subscribe function is not definedDescription: There seems to be an

I'm currently trying to retrieve a value from an array based on a specific element, and then finding the exact matching element. Unfortunately, I've encountered an error with this.getProduct(name1: string) function even though I have already impo ...

What is the method to include placeholders in password fields within Python Django forms?

I am experiencing an issue with adding placeholders to my Django form fields. Strangely, the placeholders only seem to work for the username and email fields, but not for the password fields. I have attempted using TextInput as well as a widgets dictiona ...

In Javascript, the splice method removes all elements except the specified element

I've got a straightforward script here that grabs content from an input box, converts it into an array, deletes a specific element, and then displays the remaining text. My issue is with using "splice()" to remove the item as it's deleting every ...

`How can we efficiently transfer style props to child components?`

Is there a way to pass Props in the Style so that each component has a unique background image? Take a look at this component: countries.astro --- import type { Props } from 'astro'; const { country, description } = Astro.props as Props; --- & ...

Is it possible to include multiple URLs in a single cURL request to retrieve product information?

I am trying to retrieve products from the "generic/products" URL and the "generic/all_products" URL using a single cURL request. Here is my code: <?php $ch = curl_init(); $request_url = "HTTP://www.yourdomain.com/net/WebService.aspx?"; $request_u ...

Creating a personalized upload_to function in Django

After setting up a Django system, I encountered an issue. In this setup, each user can have multiple customers with unique pages for each customer where files can be uploaded. My goal is to save these files in a directory with the path structure 'cust ...

What is the process of directing a data stream into a function that is stored as a constant?

In the scenario I'm facing, the example provided by Google is functional but it relies on using pipe. My particular situation involves listening to a websocket that transmits packets every 20ms. However, after conducting some research, I have not foun ...

Upcoming challenge regarding naming files

I came across a new problem: Error: ENOENT: file or directory not found, rename '/home/user/my-web/.next/export/en/cities/berlin.html' -> '/home/user/my-web/.next/server/pages/en/cities/berlin.html' What could be causing this issu ...

One-time PHP form submission only

On my website, I offer a variety of PDF download options. To access these downloads, I encourage visitors to sign up using a form. After signing up, they receive a direct link to the chosen PDF in their email. My goal is to streamline the process so that ...

vue utilize filtering to search through a nested array of objects within a parent array of objects

After making an API call, I receive JSON-formatted data with a specific structure like this: data = [ { name: 'John', school:[ { school_name: 'Harvard', date_attended: '2017-05-23' }, { schoo ...

What causes RangeError: Maximum call stack size exceeded when Element UI event handlers are triggered?

I'm currently working on setting up a form and validating it with Element UI. Despite closely following the documentation, I am encountering an issue where clicking or typing into the input boxes triggers a RangeError: Maximum call stack size exceeded ...

Choose ng-change within the table

I've searched everywhere for an answer to this, but I couldn't find it. I have a table that contains select and date input fields. <table id="tblCorrAction" class="table table-bordered table-striped table-hover table-condensed"> <t ...

Differences between HTML Markup in PHP and Javascript

I have been working on various tasks involving AJAX requests to fetch data from the backend of my website when a thought crossed my mind. Is it more efficient to style the HTML in PHP before sending it to the client, or should I send the data as JSON and t ...

Populate a form with database information to pre-fill the fields

So I have this web form built with HTML, and there are certain values within the form that can be changed by the user. To ensure these changes are saved, I'm storing them in a database. My goal is to have the form automatically filled with the data fr ...

Discover a step-by-step guide on showcasing SVG graphs in Vue using exclusively the SVG graph link

Currently, the only resource I have is a link to an SVG file. When opened in a browser, this link will display an SVG graph. My goal is to display this SVG graph in a Vue application: Although I attempted to implement this in Vue, it was unsuccessful. A ...

Is there a way to transmit a value from a page item on the client side to the server side in Oracle Apex without needing to submit the form?

I implemented a JavaScript function to capture the unique ROWIDs of selected rows in the GRID and send them to a specific page item. var gridView = apex.region("emp").call("getCurrentView"), selectedRecords = gridView.getSelectedRec ...

Building a table from JSON using only JavaScript.orGenerate a

I am working with a dynamic Json containing multiple keys that may vary. Here is an example: Var children = [{num = 6, name = me, phone = 7}, {num = 8, name = him, phone = 9}] My goal is to create a table with the headers (num, name, phone) Is there a w ...

The process of compressing font files (such as ArialMT.ttf) using JSZip is experiencing issues

While zipping images and HTML files works smoothly, I encountered an issue when trying to add font files for CSS. The font file is only 1kb in size, but it cannot be opened. Even after attempting to zip the font without any other files, the problem persis ...

At what point is django's values() or values_list() method executed?

According to the Django documentation, it specifies when a queryset gets evaluated. Can you tell me when ValuesListQuerySet and ValuesQuerySet are evaluated? In other words, when do they actually make a request to the database? ...

Utilizing PHP and jQuery to dynamically populate Google Maps with multiple markers

I am currently working on integrating a Google map with a database to dynamically display multiple markers using PHP and MySQL. Below is the code I have been using: <?php //This section retrieves data from the database for later use in jQuery //CREATE ...