Django中的GUI CSS选择器

时间:2018-06-08 15:19:24

标签: css ajax django django-templates

我想添加一个让用户选择“界面主题”的功能:

我在base.html中添加了一个下拉列表,以便用户可以更改所有模板中的主题。

我使用{% extends 'base.html'%}.

为我的所有html模板使用base.html

'#我的所有观点都需要这样:

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%}

我正在考虑使用AJAX,因此我可以选择用户选择的主题,但我需要在每个现有视图中添加一个函数,我不想重复那么多代码。

有更简单的方法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用Django的中间件将theme变量添加到每个请求中。请记住,您当前检索用户主题的方式将为每个请求添加额外的数据库查询。

我会将用户的主题保存在会话变量中。您的中间件可以检查是否设置了主题变量,并且只有在未设置主题变量时才从数据库中检索主题变量。你的中间件看起来像这样:

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

然后,您可以在所有视图和模板中访问request.session.theme

我要问的另一个问题是:为什么要存储哪个用户在MyThemeModel而不是User模型上使用哪个主题?如果您将其存储在用户模型中,则可以使用request.user.theme,而根本不需要中间件。