【问题标题】:Trying to render data from database in a html table using Django framework尝试使用 Django 框架在 html 表中呈现数据库中的数据
【发布时间】:2019-12-26 12:12:57
【问题描述】:

我创建了一个 GPU 数据库,我想使用 Django MVT 以 HTML 格式呈现它。

这是 'graphicsCard' 中的“urls.py”脚本 ['graphicsCard' 是应用名称]

from django.urls import path
from . import views
urlpatterns = [
    path('products', views.productViews, name='products')
]

graphicsCard的

views.py

from django.shortcuts import render
from .models import Products
# Create your views here.
def productViews(request):
    allproduct = Products.objects.all()
    context = {
        'allproduct': allproduct
    }
    return render(request, 'Products.html', context)

名为“products.html”的html模板

{% extends 'homepage.html' %}
<!-- {% load %} -->
{% block content %}
<div class="row">

    <div class="col-2 bg-info">
        Menu
    </div>    
        <table class="col-10 table table-dark py-0 my-table">
            <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">First</th>
                    <th scope="col">Last</th>
                    <th scope="col">Handle</th>
                </tr>
            </thead>
            <tbody>
               {% for x in allproduct %}
                    <tr>
                        <td>{% x.name %}</td>
                        <td>First</td>
                        <td>Last</td>
                        <td>Handle</td>
                    </tr>
               {% endfor %}
            </tbody>
        </table>

</div>

{% endblock %}

当我运行 python manage.py shell 并输入

product = Products.objects.all()
product[1].name

它从数据库发送数据,但我无法弄清楚这个错误,称为 “模板渲染期间出错”,然后是

“第 21 行的块标签无效:'x.name',预期为 'empty' 或 'endfor'。您忘记注册或加载此标签了吗?”

【问题讨论】:

  • 不是块 {% x.name %} 是 {{ x.name }}

标签: python django


【解决方案1】:

你需要{{ }}来渲染模板中的变量


   {% for x in allproduct %}      
       {{ x.name }}
     {% endfor %}
   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 2016-09-04
    相关资源
    最近更新 更多