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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵