weixin_33737774 2018-06-08 15:19 采纳率: 0%
浏览 116

Django中的GUI CSS选择器

I want to add a functionality which let the user choose a "interface theme':

I added a dropdown in my base.html so the user can change the theme in all the templates.

I use a base.html for all my html templates using {% extends 'base.html'%}.

'# All my views will need 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' %}" />
{% else if theme = 'theme 2'%}
<link rel="stylesheet" type="text/css" href="{% static 'theme2.css' %}" />
{% else if theme = 'theme 3'%}
<link rel="stylesheet" type="text/css" href="{% static 'theme3.css' %}" />
{% endif%}

I'm thinking of using AJAX so I can take the theme the user choose but then I will need to add a function in each existing view and I don't want to repeat that much of code.

Is there an easier way to do this?

  • 写回答

1条回答 默认 最新

  • weixin_33698043 2018-06-08 15:38
    关注

    You can use Django's middleware to add your theme variable to every request. Keep in mind that the way you are currently retrieving the user's theme will add an extra database query to every request.

    I would save the user's theme in a session variable instead. Your middleware can check whether the theme variable is set, and only if it is not set retrieve it from the database. Your middleware would look like this:

    if not request.session.theme:
        request.session.theme = MyThemeModel.objects.filter(user=self.request.user).first().theme
    

    You can then access request.session.theme in all your views and templates.

    Another question I would have is: why are you storing which user is using which theme on your MyThemeModel instead of on your User model? If you stored it on your user model you could simply use request.user.theme and you wouldn't need the middleware at all.

    评论

报告相同问题?

悬赏问题

  • ¥15 k210烧入flash报错error:2005
  • ¥15 GIS土地利用预测FLUS模型
  • ¥15 visual studio code打不出来中文双引号
  • ¥20 关于#matlab#的问题:ps:完美符合要求有打赏(相关搜索:自适应)
  • ¥15 声音感应灯,问题出在哪里
  • ¥15 关于#matlab#的问题:(0,0)上的贝塞尔曲线,0)上的贝塞尔曲线,并使用自适应积分计算其从t=0到不大于1的任意值区间的弧长
  • ¥20 关于#r语言#rda分析作图的问题,请各位专家解答!
  • ¥50 找回 股票行情系统的资源问题
  • ¥15 gwas 分析-plink 检查人口分层出现下面问题
  • ¥15 关于#matlab#的问题:需要 MATLAB 运行程序,对比四个多址通信方式(TDMA,FDMA,CDMA,OFDMA)的抗噪声性能