【问题标题】:Change CSS stles from view in Django从 Django 中的视图更改 CSS 样式
【发布时间】:2021-12-23 22:33:50
【问题描述】:

对不起,如果这是一个明显的问题,我是 django 的新手,还在学习。 我正在创建一个总共包含 6 张图片的网站。在从views.py 传递它的图像ID 之前,网站中的图像应该保持不可见。

我有一个模板 index.html 页面和视图,当访问此 url 时加载 localhost/imageid

我现在需要的是在访问其 url 时使图像可见。例如,如果用户访问 localhost/1。 QR 码 1 应可见。我还存储了所有访问图像的状态。因此,如果用户再次访问该网站并转到 localhost/2 它应该使图像 1 和 2 可见。我正在使用会话来存储状态。我只需要一种使图像可见的方法。

谢谢你

【问题讨论】:

    标签: python html css django


    【解决方案1】:

    取决于所以基本观点是:

    from django.views.generic import TemplateView
    
    class MyView(TemplateView):
        template_name = 'my_html.html'
    
        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            context['img_id'] = self.kwargs.get('pk')  # this is whatever the variable is named in the URL.
            return context
    

    html 会是这样的:

    <body>
        {%if img_id == 1 %}
            <img src="image1path">
        {%elif img_id == 2 %}
            <img src="image2path">
        {% endif %}
    </body>
    

    更好的方法是将图像存储在数据库中并从模型中获取图像路径,然后您可以在上下文中获取它并在模板中引用它,而不是使用 if 语句。

    【讨论】:

      猜你喜欢
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      • 2014-08-27
      • 1970-01-01
      • 2019-07-23
      • 2021-03-31
      • 2014-03-17
      相关资源
      最近更新 更多