Sha*_* S. 2 python django django-templates
我一直在寻找在视图/模板中显示 Django 模型数据的方法。我仍然只是一个初学者,但已经阅读了大量的 stackoverflow 来获取知识。
我从这个线程中获取了我想要做的事情的实现:显示对象 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>
在模板.html 中
我尝试为模型中的每个字段添加详细名称,但这不是明显的问题。附在粘贴箱中的是我的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>
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
使用{{field.verbose_name}}而不是{% get_value_from_key d field %}在模板中使用这种方法工作正常并经过测试:
In [1]: from django.template import Template,Context\n\nIn [2]: t=Template("""""")\n\nIn [3]: t=Template("""{% for field in fields %}\n ...: <td>{{field.verbose_name}}</td>\n ...: {% endfor %}""")\n\nIn [4]: from h.models import MyClass\n\nIn [5]: c = Context({"fields":MyClass._meta.fields,})\n\nIn [6]: t.render(c)\nOut[6]: u\'\\n <td>ID</td>\\n \\n <td>Name</td>\\n\nRun Code Online (Sandbox Code Playgroud)\n\n首先,您需要根据 django doc注册自定义模板标签注册自定义模板标签:
\n\n应用程序应包含一个目录,与、等templatetags处于同一级别。如果 \xe2\x80\x99t 不存在,请创建它 - 不要\xe2\x80\x99t 忘记该文件以确保该目录被视为 Python package.\n然后创建 python 文件,将其命名为您想要的文件名models.pyviews.py__init__.pymytag.py\n在模块顶部附近,输入以下内容:
from django import template\n\nregister = template.Library()\nRun Code Online (Sandbox Code Playgroud)\n\n注册标签使用函数助手simple_tag\n在函数之前添加:
@register.simple_tag\nRun Code Online (Sandbox Code Playgroud)\n\n然后输入您的标签作为函数,它需要两个参数instance和name(即归档名称)然后返回verbose_name:
def get_verbose_name(instance):\n return instance.verbose_name\nRun Code Online (Sandbox Code Playgroud)\n\n把所有的放在一起:
\n\nfrom django import template\n\nregister = template.Library()\n@register.simple_tag\ndef get_verbose_name(instance, field_name):\n return instance.verbose_name\nRun Code Online (Sandbox Code Playgroud)\n\n然后在模板加载中使用它mytag模块中使用它,请使用标签:
{% load mytag %} \n{% get_verbose_name field_instance %}\nRun Code Online (Sandbox Code Playgroud)\n\n返回 field_instance.verbose_name
\n| 归档时间: |
|
| 查看次数: |
6262 次 |
| 最近记录: |