我一直在寻找在 View /模板中显示 Django 模型数据的方法。我仍然只是一个初学者,但已经阅读了大量的 stackoverflow 来获取知识。
我从这个线程中获取了我想要做的事情的实现:Display table of objects django
输入template.html和views.py(稍微修改我的views.py - 将MyModel更改为环境模型)后,我收到错误:
"Invalid block tag on line 5: 'get_verbose_name', expected 'empty' or 'endfor'. Did you forget to register or load this tag?"
此错误指的是 <th>{% get_verbose_name field %}</th>
在 template.html 中
我尝试为模型中的每个字段添加详细名称,但这不是明显的问题。附在粘贴箱中的是我的views.py、models.py 和template.html。
我的views.py和template.html几乎与链接的stackoverflow线程中检查的解决方案完全相同。我的问题基本上是理解为什么会出现此错误,以及如何解决它
感谢您的帮助
tables.html
<table>
<thead>
<tr>
{% for field in cached_fields %}
<th>{% get_verbose_name field %}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for d in data %}
<tr>
{% for field in fields %}
<td>{% get_value_from_key d field %}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
View .py
from __future__ import unicode_literals
from django.views import generic
from django.shortcuts import render, render_to_response, get_object_or_404, redirect
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpRequest, HttpResponse
from django.template import RequestContext
import simplejson as json
#from appDatabase.forms import *
from . import forms;
from . import models;
class AppTable(generic.TemplateView):
template_name = "appDatabase/tables.html"
def index(request) :
fields = Environment._meta.fields
data = json.loads(serializers.serialize("json", Environment.objects.all()))
def parse_data(data):
result = []
# flatten the dictionary
def flatten_dict(d):
"""
Because the only nested dict here is the fields, let's just
remove the 'fields' suffix so that the fields can be loaded in
template by name
"""
def items():
for key, value in d.items():
if isinstance(value, dict):
for subkey, subvalue in flatten_dict(value).items():
yield subkey, subvalue
else:
yield key, value
return dict(items())
for d in data:
# change the 'pk' key name into its actual name in the database
d[Environment._meta.pk.name] = d.pop('pk')
# append the flattend dict of each object's field-value to the result
result.append(flatten_dict(d))
return result
context_instance = RequestContext(request, {
'data' : parse_data(data),
'fields' : fields, })
return TemplateResponse(request, 'tables.html', context_instance)
模型.py
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
import uuid
from django.contrib.auth.models import User
from django.db import models
from django import forms
from django.forms import ModelForm;
# Create your models here.
class Environment(CommonInfo):
environment_Type = models.CharField(verbose_name ="Environment Type", max_length=10)
environment_Name = models.CharField(verbose_name ="Environment Name", max_length=10)
最佳答案
- 非常简单的方法
使用{{field.verbose_name}}
而不是{% get_value_from_key d field %}
在您的模板中,这种方法工作正常并经过测试:
In [1]: from django.template import Template,Context
In [2]: t=Template("""""")
In [3]: t=Template("""{% for field in fields %}
...: <td>{{field.verbose_name}}</td>
...: {% endfor %}""")
In [4]: from h.models import MyClass
In [5]: c = Context({"fields":MyClass._meta.fields,})
In [6]: t.render(c)
Out[6]: u'\n <td>ID</td>\n \n <td>Name</td>\n
- 非常复杂的方法
首先,您需要根据 django doc 注册自定义模板标签。 :
应用程序应包含 templatetags
目录,与models.py
同级, views.py
等等。如果尚不存在,请创建它 - 不要忘记 __init__.py
文件以确保该目录被视为 Python 包。
然后创建 python 文件,将其命名为您想要的文件名 mytag.py
在模块顶部附近,放置以下内容:
from django import template
register = template.Library()
注册标签使用函数助手simple_tag
在你的函数之前添加:
@register.simple_tag
然后输入您的标签作为函数,它需要两个参数 instance
和name
(即归档名称)然后返回 verbose_name
:
def get_verbose_name(instance):
return instance.verbose_name
将所有内容放在一起:
from django import template
register = template.Library()
@register.simple_tag
def get_verbose_name(instance, field_name):
return instance.verbose_name
然后在模板加载中使用它 mytag
模块使用标签:
{% load mytag %}
{% get_verbose_name field_instance %}
返回field_instance.verbose_name
关于python - "django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 5: ' get_verbose_name ', expected ' 空 ' or ' endfor '. ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40164635/