简体   繁体   English

Django 模板不保留 OrderedDict

[英]Django Template not preserving OrderedDict

The function returns an ordered list该函数返回一个有序列表

    my_olist = OrderedDict() 
    my_olist['bananas'] = 3
    my_olist['apples'] = 1
    ..
    return my_olist

in the view.py I confirmed the order is maintained在 view.py 中,我确认订单已维护

   returned_ordered_list = mylist()  # this is still ordered
    request.session['results'] = {...
             'ordered_list': returned_ordered_list
}
return render(request, HttpResponseRedirect(reverse('myapp:resultspage',))

However in the HTML template resultspage, the order is no longer maintained但是在 HTML 模板结果页面中,不再维护顺序

{% for key, value in ordered_list.items %} 
<b>{{key}}:</b> {{value}} <br>
 {% endfor %}

I've seen a solution working for orderedDict but they did not use HttpResponseRedirect.我见过一个适用于 orderedDict 的解决方案,但他们没有使用 HttpResponseRedirect。

If you store an ordered dict in the session, then the order will not be preserved.如果您在会话中存储一个有序的字典,那么该顺序将不会被保留。 By default, the Django session is serialized as JSON.默认情况下,Django 会话被序列化为 JSON。 When it is deserialized, you get a regular dictionary, so the ordering will be lost.当它被反序列化时,你会得到一个普通的字典,所以顺序会丢失。

If the ordering is important, and you don't have to access the dictionary values by key, then you could use a list of tuples instead:如果顺序很重要,并且您不必按键访问字典值,那么您可以改用元组列表:

my_olist = [] 
my_olist.append(('bananas', 3))
my_olist.append(('apples', 1))

Then update the template to loop through the list:然后更新模板以循环遍历列表:

{% for key, value in ordered_list %}

firebase data火力库数据Firebase 实时存储的图像

python.py蟒蛇.py

firebase = Firebase(config)
db = firebase.database()
x = db.child("Home page").get()
output = {
     'value':x
   }
return render(request, "index.html",output)

index.html索引.html

 <p class="m-t-10 m-b-0 font-18 wow fadeInUp " id="K">{{ value.val.KhadiMadeFashionable } </p> 

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

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