Django CSS graphical interface for selecting styles

I am looking to implement a feature that allows users to select an "interface theme":

To enable users to change the theme across all templates, I have created a dropdown in my base.html.

For all my HTML templates, I utilize a base.html file by extending it using {% extends 'base.html'%}.

'# All views will require this:

theme = MyThemeModel.objects.filter(user=self.request.user).first().theme

return render(request, 'mytemplate.html', {'theme': theme})

'#base.html

{% if theme == 'theme 1'%}
<link rel="stylesheet" type="text/css" href="{% static 'theme1.css' %}" />
{% elif theme == 'theme 2'%}
<link rel="stylesheet" type="text/css" href="{% static 'theme2.css' %}" />
{% elif theme == 'theme 3'%}
<link rel="stylesheet" type="text/css" href="{% static 'theme3.css' %}" />
{% endif%}

I am considering utilizing AJAX to retrieve the selected theme from the user. However, I am concerned about having to add a function to each existing view. I aim to minimize code repetition. Is there a simpler way to achieve this?

Answer №1

To easily add your custom theme variable to every request in Django, you can utilize middleware. However, be cautious of the extra database query being made for each request when retrieving the user's theme. To optimize this process, consider saving the user's theme in a session variable instead. This way, the middleware can first check if the theme variable is already set in the session before querying the database. Here's an example implementation of the middleware logic:

if not request.session.theme:
    request.session.theme = MyThemeModel.objects.filter(user=self.request.user).first().theme
By accessing request.session.theme in your views and templates, you can ensure a smoother and more efficient process. Additionally, it might be beneficial to reconsider storing user-theme associations on the MyThemeModel rather than directly on the User model. Storing this information on the user model itself could eliminate the need for middleware entirely by allowing direct access to request.user.theme.

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

Invoking a widget through ajax in SocialEngine

Is it feasible to initiate an ajax call on a SocialEngine Widget? While I am aware that ajax calls can be made on controller methods, I am unsure about widgets. If this is possible, could someone please provide guidance on how to accomplish this? ...

The mobile page is refusing to scroll, causing all the text to bunch up at the top of the screen

After learning HTML/CSS/Js/PhP over a few months, I recently completed my first website. I am facing an issue with one of the pages on my website when viewed on a mobile device. The parallax scrolling header image does not scroll either horizontally or ve ...

Is it possible to insert a second hyperlink into a JavaScript-occupied anchor?

Check out my reference page at: To change the content in a 'containerarea' div, I am utilizing Dynamic Drive's "Dynamic Ajax" script. Below is an example of the anchor code used: <a href="javascript:ajaxpage('videos-maintenance/app ...

Combining the p class with flexbox for optimal layout design

I have four flexed container boxes and I am looking to add text below them in a row. Does anyone have suggestions on how I can achieve this alignment, as well as tips for optimizing the code? .container { display: flex; flex-direction: row; just ...

The div element is failing to occupy the entire page

I have encountered an issue where I created two small blocks, but they do not start from the screen edges. Instead, they take up space from the left, right, and top as well. Here is my code: HTML <body> <div id="header"></div> & ...

The .ajaxSubmit function in jquery.form.js seems to be malfunctioning when using the data option

I'm currently working with the jQuery plugin jquery.form.js and I'm looking to programmatically submit a form while including a file. Although I've set up the code and options to work with $.ajax, it's not functioning with .ajaxSubmit. ...

Is it possible to swap two classes with each other using jQuery?

I am trying to implement a tree view with the following code snippet. Within the tree view, there are spans that have either the CollOpen or CollClosed class assigned to them. How can I toggle between these two classes on click for each span? .tree ...

What is the process for assigning a PHP function's return value to a JavaScript variable?

Is there a way to retrieve a value from a PHP function and assign it to a JavaScript variable? As shown in the following example: PHP: // Destination folder for downloaded files $date = date('m.d.y'); mkdir("uploads/" . $date, 0777, true); $ ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

Manage several scrolls using overflow:auto

There are numerous popups on a page with the overflow:auto property. The structure is as follows - <div id="popup1"> <div>SomeHTMLSTRUC</div> <div>SomeHTMLSTRUC</div> <ul class="scroll"></ul> </div> ...

Emphasizing Text Within Div Element

Imagine having a div element structured as such: <div id="test" class="sourcecode"> "Some String" </div> Can CSS and JavaScript be utilized to highlight a specific portion of that string based on a search query? For instance, if the search q ...

Delaying CSS Keyframe animations

I'm having trouble getting the color squares in my table to appear one by one. I want each color to show up, then disappear, followed by the next color appearing and disappearing, creating a light sequence effect. Any advice or assistance would be gre ...

techniques for accessing HTML source code through an AJAX call

I am trying to retrieve the HTML source of a specific URL using an AJAX call, Here is what I have so far: url: "http://google.com", type: "GET", dataType: "jsonp", context: document.doctype }).done(function ...

Empty value for $_POST variable following xmlhttp request

When my code makes an xmlhttp request to a php file with an ID for record deletion from the database, I encounter an issue. The error message 'comicID' is undefined shows up when attempting to delete. This signifies that the variable containing t ...

The Ajax Process continues to run even after the user has navigated away from the page

Currently, I have a JavaScript function that refreshes a specific section of a Rails-generated view every 2.5 seconds using a JS request to update a basic progress bar. function refreshPage(){ $.ajax({ type:"GET", dataType:"script" }) } s ...

Repeatedly Triggered JQuery AJAX Calls

On my web page, I have implemented a feature that allows users to search for an address using a GIS server's web-service. This functionality is triggered by a button click event which calls a JQuery AJAX method. Upon successful retrieval of address da ...

Techniques for animating background image using jQuery

Hello there! I'm currently experimenting with animating a background image using jQuery. Despite following a tutorial, I haven't been successful in getting my test page to work as intended. The blue Facebook icon displays, but it doesn't ani ...

The Ajax delete script is malfunctioning and not deleting records properly

I am currently facing an issue with my Ajax script for deleting entries. The script is working as intended, however, when I click the delete button, only the first entry in the list of all records gets deleted. Interestingly, upon refreshing the page, the ...

What is the best way to eliminate the outer gutter in a 3-column grid using Bootstrap 3?

Check out this fiddle for more information. http://jsfiddle.net/Nb5C7/ I am curious about the blue gutter on the ends, which seems to be caused by auto margin. How can I get rid of it? In another example provided here , I was able to remove the gutter u ...

The value of a variable decreases upon being utilized in an Ajax API call

My tempid variable seems to lose some of its values when passed into the second API call. Despite logging the variable to console (console.log(tempid)) where it appears fine, once placed in the API call it only retains some of its value. I'm uncertain ...