我已经定义了模型和视图。我想显示数据库中存在的项目。但是,脚本未显示任何内容。哪里出问题了?请查看文件的模型,视图和html模板的定义,以尝试使用 for 循环显示数据库中的项目。
models.py
from django.db import models
from bifrost.models import CustomUser
# Create your models here.
# Model Projektu
class Project(models.Model):
PROJECT_TYPE = (
('SCR', 'Scrum'),
('KAN', 'Kanban'),
)
project_key = models.CharField(max_length=8, primary_key=True)
project_name = models.CharField(max_length=160)
project_type = models.CharField(max_length=10, choices=PROJECT_TYPE, null=True)
date_created = models.DateField(null=True)
# Definicja nazwy modelu w Adminie Django
def __str__(self):
return self.project_name
views.py
from django.views.generic import ListView
from django.shortcuts import render
from .models import Project
# Create your views here.
class ProjectListView(ListView):
model = Project
template_name = 'project-list.html'
contect_object_name = 'projects_list'
def projectslist(request):
projects = Project.objects.all()
return render(request, 'project_list.html', {'projects': projects})
project-list.html模板
{% extends 'base.html' %}
<h1 class="h3 mb-2 text-gray-800">{% block title %}Projects{% endblock title %}</h1>
{% block content %}
<!-- DataTales Example -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">List of Projects</h6>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Project Key</th>
<th>Name</th>
<th>Type</th>
<th>Created</th>
</tr>
</thead>
<!-- <tfoot>
<tr>
<th>Project Key</th>
<th>Name</th>
<th>Type</th>
<th>Created</th>
</tr>
</tfoot> -->
<tbody>
{% for project in projects_list %}
<tr>
<td>{{ project.project_key }}</td>
<td>{{ project.project_name }}</td>
<td>{{ project.project_type }}</td>
<td>{{ project.date_created }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}
调试器未显示任何问题。 Pylint仅显示小建议,也没有错误。
答案 0 :(得分:1)
{% for project in projects_list %}
在模板中更改此行,因为您已将项目作为上下文的键传递,并且您正在使用 projects_list 。
尝试{% for project in projects %}
它应该可以工作。
答案 1 :(得分:1)
您将从视图文件中将项目作为参数传递给return render(request, 'project_list.html', {'projects': projects})
,在模板文件中,您将通过 projects_list 访问它。返回任何东西。
在您的模板文件中替换:
{% for project in projects_list %}
具有:
{% for project in projects %}
它将起作用。