简体   繁体   English

Django中的Python for循环在字典中返回随机值

[英]Python for loop in Django returning random value in dictionary

I have a Wagtail page displaying the routing link block inside it and I'm adding an icon to the routing link model to display with title in the block on main page.我有一个 Wagtail 页面,其中显示了路由链接块,我正在向路由链接模型添加一个图标,以在主页上的块中显示标题。 In the main page I'm getting the context for uploaded file field for icon as below:在主页中,我获得了图标的上传文件字段的上下文,如下所示:

def get_context(self, request):
   context = super().get_context(request)
   routing_links_queryset = self.routing_links
   for link in routing_links_queryset:            
      i_link = link.link_icon
      if i_link:
           try:
              with i_link.icon.open() as file_obj:
                  data = file_obj.read()
                  data = data.decode("utf-8")                          
                  context["iconlink_data"] = data
           except OSError:
                pass
   return context

link_icon is field in routing_links model and icon is Filefield in Icon model. link_icon 是routing_links 模型中的字段,icon 是Icon 模型中的Filefield。 Now this is returning the context on the main page but if there are 2 routing link blocks on the main page, it will render the same icon for both.现在这将返回主页上的上下文,但如果主页上有 2 个路由链接块,它将为两者呈现相同的图标。

Do I have to append the context in each iteration?我是否必须在每次迭代中附加上下文? How exactly I could append in this case or any alternative way to do this?在这种情况下我究竟可以如何追加或任何替代方法来做到这一点?

Modify get_context to add all the icons to a context["links"] dict, then loop through it in the template:修改 get_context 以将所有图标添加到 context["links"] dict,然后在模板中循环遍历它:

def get_context(self, request):
    context = super().get_context(request)
    routing_links_queryset = self.routing_links
    context["links"] = []
    for link in routing_links_queryset: 
        link_dict = {"link_obj": link}
        i_link = link.link_icon
        if i_link:
            try:
                with i_link.icon.open() as file_obj:
                    data = file_obj.read()
                    data = data.decode("utf-8")                          
                    link_dict["iconlink_data"] = data
        context["links"].append(link_dict)
            except OSError:
                pass
    return context

in the Django Template it would look something like:在 Django 模板中,它看起来像:

{% for link_dict in links %}
   {{ link_dict.link_obj }}
   {{ link_dict.link_obj.link_field }}
   <svg height="35" width="35" style="display: inline">{{ link_dict.iconlink_data|safe }}</svg>
{% endfor %}

(Added as an answer for formatting) (添加为格式化的答案)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM