python - 模板中的字段名称和值

标签 python django django-templates

我想在我的模板中显示类似的内容:

Name: John

Age: 18

City: New York

例如,使用以下代码:

views.py

def person_details(request,pk):
   person = get_object_or_404(Person, id=pk)
   return render(request, 'template.html', {'person': person, 'person_fields': person._meta.get_fields()})

template.html

{% for field in person_fields %}        
     <div class="col-4 form-group">            
         <p><strong>{{ field.verbose_name }}:</strong> {{ person[ field.name ]  }}</p>             
     </div>
{% endfor %}

这在Python中可能吗?我问这个问题是因为我有一个大约有 20 个字段的模型,并且在模板中对字段进行硬编码会有点困难。

最佳答案

您可以使用 Django 的 to-python 查询集序列化程序。

只需将以下代码放入您的 View 中即可:

from django.core import serializers
data = serializers.serialize( "python", SomeModel.objects.all() )

然后在模板中:

{% for instance in data %}
    {% for field, value in instance.fields.items %}
        {{ field }}: {{ value }}
    {% endfor %}
{% endfor %}

它的巨大优势是它可以处理关系字段。

对于字段子集,请尝试:

data = serializers.serialize('python', SomeModel.objects.all(), fields=('name','size'))

关于python - 模板中的字段名称和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53154593/

相关文章:

python - "dict-like"在 Python 中是什么意思?

python - SyntaxError : 'break' outside loop, 错误仅在树莓派 3 上给出,而不是在 pc 上

python - 如何在django中获取上传的文件名

python - 带有回滚仿真的 Django TransactionTestCase

python - Django 模板标签返回 True 或 False

Python 抓取响应数据

python - Django 模板在无效的编辑个人资料表单上呈现更改的用户名

python - 语法错误 : keyword can't be an expression (views. py)

python - 在设置中使用 debug=false 的 Django-Compress 给出错误

python - 在 Pyomo 中获取目标的梯度和 Hessian