python 这里有什么问题?在 Django 模板中迭代字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2218388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:05:50  来源:igfitidea点击:

What's wrong here? Iterating over a dictionary in Django template

pythondjangodjango-templates

提问by AP257

I'm trying to iterate over a dictionary of model values in a Django template - I want to list the verbose_name of each model field alongside its value.

我正在尝试遍历 Django 模板中的模型值字典 - 我想列出每个模型字段的 verbose_name 及其值。

Here's what I have in models.py:

这是我在models.py中的内容:

class Manors(models.Model):
    structidx = models.IntegerField(primary_key=True, verbose_name="ID")    
    county = models.CharField(max_length=5, null=True, blank=True, verbose_name="County")   

    def get_fields(self):
            d = {}
            #d["database"] = "pubs"
            #d["uid"] = "sa"
            for field in Manors._meta.fields:
                d[field.verbose_name(self)] = field.value_to_string(self)
            return d

And in views.py:

在 views.py 中:

    manor_stats = Manors.objects.get(structidx__exact=id)
    return render_to_response('template.html', { 'place' : place, 'manor_stats' : manor_stats }, context_instance = RequestContext(request))

And in the template:

在模板中:

<h4>Statistics</h4>
<ul>
 {% for key, value in manor_stats.get_fields %}
 <li> {{ key }}: {{ value }} </li>
{% endfor %}
</ul>

But I just get a weird, distorted-looking list like:

但我得到了一个奇怪的、看起来扭曲的列表,比如:

u: i
d: a

It doesn't even work if I use hard-coded values in models.py (as shown commented out above).

如果我在 models.py 中使用硬编码值,它甚至不起作用(如上面注释所示)。

What's wrong here? Been trying to work this out for hours:(

这里有什么问题?几个小时以来一直试图解决这个问题:(

---------- UPDATED ---------------

- - - - - 更新 - - - - - - - -

Trying with

尝试

def get_fields(self):
        d = {}
        for field in Manors._meta.fields:
            d[field.verbose_name(self)] = { "verbose": field.verbose_name(self), "value": field.value_to_string(self) }
        return d

and in template:

并在模板中:

<h4>Statistics</h4>
<ul>
 {% for key, value in manor_stats.get_fields %}
 <li> {{ key }}: {{ value }}</li>
{% endfor %}
</ul>

just produces a blank list....

只产生一个空白列表....

回答by MattH

To iterate a dictionary wouldn't you need:

迭代字典不需要:

<h4>Statistics</h4>
<ul>
 {% for key, value in manor_stats.get_fields.items %}
 <li> {{ key }}: {{ value }}</li>
 {% endfor %}
</ul>

But I'd suggest retrieving the dictionary from the function first:

但我建议先从函数中检索字典:

Views.py:

视图.py:

    manor_stats = Manors.objects.get(structidx__exact=id).get_fields()
    return render_to_response('template.html', { 'place' : place, 'manor_stats' : manor_stats }, context_instance = RequestContext(request))

And then:

接着:

<h4>Statistics</h4>
<ul>
 {% for key, value in manor_stats.items %}
 <li> {{ key }}: {{ value }}</li>
 {% endfor %}
</ul>

But only because I'm not that familiar with how much dereferencing the templating system can do. Seeing as you know how to deference it you're saving the effort of having the renderer work it out.

但仅仅是因为我不太熟悉模板系统可以做多少取消引用。看到您知道如何尊重它,您就可以节省渲染器解决它的工作量。

回答by Ignacio Vazquez-Abrams

Iterating over a dict yields its keys. I don't know why Django thinks you want to do an incomplete sequence expansion on the key name instead of throwing an exception, but I'll chalk it up to ANOTHERone of Django's template engine's quirks.

迭代一个 dict 会产生它的键。我不知道为什么 Django 认为您想要对键名进行不完整的序列扩展而不是抛出异常,但我会将其归结为另一个 Django 模板引擎的怪癖。

Anyways, yes, get keyfrom the dict in your for loop, then use keyand dict.keyinside it.

不管怎么说,是的,获得key从字典中的for循环,然后使用keydict.key里面。

回答by Bjorn

You're getting the weird results because I think you're iterating over a string's characters. A for loop in django templates isn't the same as in python. Try using an object and iterating via property accessors for object in my objectsand then use object.prop1object.prop2instead.

您得到了奇怪的结果,因为我认为您正在迭代字符串的字符。django 模板中的 for 循环与 python 中的不同。尝试使用对象并通过属性访问器进行迭代for object in my objects,然后object.prop1object.prop2改为使用。