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.

    评论

报告相同问题?