简体   繁体   中英

How to set variable inside django template with javascript and pass it to views.py?

I want to add a dark mode option to my django website, when you press a button I want to set a variable dark-mode to True and when you press again it sets dark-mode to False using javascript, and at views.py it will set the template-name as home-dark.html or home-light.html according to the dark-mode variable, how can I achieve this?

In case you need to know, I use Materialize CSS

Thanks from now

You could pass it in the url and have a condition in your view , for example:

# your button should href to domain.com/your_view/?mode={your variable}
# then in your view
if request.GET.get('mode') == 'dark':
    return render(request, 'home-dark.html')
return render(request, 'home-light.html')

But that will work for one page only, if you want to keep that for the whole session I suggest you add it in request.session and then you can access it in any view. For example:

# in the above view before returning:
request.session['browse_mode'] = 'dark'

# then in all your views
if request.session.get('browse_mode') == 'dark':
    return render(request, 'dark-mode.html')
return render(request, 'light-mode.html')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM