AP2*_*257 7 python django django-templates
我试图在Django模板中迭代模型值的字典 - 我想列出每个模型字段的verbose_name及其值.
这是我在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
Run Code Online (Sandbox Code Playgroud)
在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))
Run Code Online (Sandbox Code Playgroud)
在模板中:
<h4>Statistics</h4>
<ul>
{% for key, value in manor_stats.get_fields %}
<li> {{ key }}: {{ value }} </li>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)
但我只是得到一个奇怪的,扭曲的列表,如:
u: i
d: a
Run Code Online (Sandbox Code Playgroud)
如果我在models.py中使用硬编码值,它甚至不起作用(如上所示).
这有什么不对?一直在努力工作几个小时:(
- - - - - 更新 - - - - - - - -
试着用
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
Run Code Online (Sandbox Code Playgroud)
并在模板中:
<h4>Statistics</h4>
<ul>
{% for key, value in manor_stats.get_fields %}
<li> {{ key }}: {{ value }}</li>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)
只是产生一个空白列表....
Mat*_*ttH 29
要迭代字典,您不需要:
<h4>Statistics</h4>
<ul>
{% for key, value in manor_stats.get_fields.items %}
<li> {{ key }}: {{ value }}</li>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)
但我建议先从函数中检索字典:
Views.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))
Run Code Online (Sandbox Code Playgroud)
然后:
<h4>Statistics</h4>
<ul>
{% for key, value in manor_stats.items %}
<li> {{ key }}: {{ value }}</li>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)
但这只是因为我不熟悉模板系统可以做多少解除引用.看到你知道如何尊重它,你就节省了让渲染器解决问题的努力.
| 归档时间: |
|
| 查看次数: |
18526 次 |
| 最近记录: |