我一直在寻找在视图/模板中显示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>
我试图在模型中的每个字段中添加一个详细的名称,但这不是明显的问题。附在pastebin中的是我的views.py,models.py和template.html。
我的views.py和template.html几乎与链接的stackoverflow线程中检查的解决方案完全相同。我的问题基本上是理解为什么存在这个错误,以及我如何解决它
感谢您的帮助
<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>
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)
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)
答案 0 :(得分:3)
在您的模板中使用{{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 %}
return field_instance.verbose_name