I am trying to add a themes for users in my Django project. Users can choose between dark mode and light mode.
So in the base.html, I have set the links to be as following:
<link id="mystylesheet" href="{% static 'css/app-light.css' %}" type="text/css" rel="stylesheet">
<!-- Mode -->
<div id="mode" class="section" style="padding-top: 1rem; padding-bottom: 3rem;text-align: right">
<button onclick="swapStyles('app-light.css')" type="button" class="btn btn-secondary">Light Mode</button>
<button onclick="swapStyles('app-dark.css')" type="button" class="btn btn-dark">Dark Mode</button>
</div>
<!-- Mode -->
I have started a new app called mode with following models.py:
class Setting(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="mode",null=True,blank=True)
name = models.CharField(max_length=200, null=True)
value = models.CharField(max_length=200)
def __str__(self):
return self.name
here is the javascript
<script type="text/javascript">
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
var cssFile = "{% static 'css' %}"
function swapStyles(sheet){
document.getElementById('mystylesheet').href = cssFile + '/' + sheet
localStorage.setItem('theme', sheet)
updateTheme(sheet)
}
function loadSettings(){
//Call data and set local storage
var url = "{% url 'mode:user_settings' %}"
fetch(url, {
method:'GET',
headers:{
'Content-type':'application/json'
}
})
.then((response) => response.json())
.then(function(data){
console.log('Data:', data)
var theme = data.value;
if (theme == 'light.css' || null){
swapStyles('light.css')
}else if(theme == 'dark.css'){
swapStyles('dark.css')
}
})
}
loadSettings()
function updateTheme(theme){
var url = "{% url 'mode:update_theme' %}"
fetch(url, {
method:'POST',
headers:{
'Content-type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'theme':theme})
})
}
</script>
Here is the urls.py
app_name = 'mode'
urlpatterns = [
path('user_settings/', views.userSettings, name="user_settings"),
path('update_theme/', views.updateTheme, name="update_theme"),
]
I have difficulty setting the user settings views.py to reflect when the user is logged in, however, the updated theme is working ok.
def userSettings(request):
user = request.user
setting = getattr(user, 'setting', None)
def updateTheme(request):
data = json.loads(request.body)
theme = data['theme']
user = request.user
setting = Setting.objects.update_or_create(
user=user, defaults={'value': theme}, name='theme')
print('Request:', theme)
return JsonResponse('Updated..', safe=False)
My question: How can I configure the user settings
to be set that the user who is currently logged in to have a settings as light mode as a default and if he choose to have it a dark mode to be set in the data base in all the pages and when it is on dark mode and the user choose light mode to be set in the data base.