如何使用Django和模板标签正确地从数据库中提取

问题描述 投票:0回答:2

我正在尝试使用Django创建一个Web应用程序,显示有关员工和日程安排的信息。我有存储在Django数据库中的员工的数据,但当我尝试从中拉出并在表中显示信息时没有任何反应。我没有收到错误,所以我不确定我是否使用了正确的方法。

我之前没有使用过Django所以我不确定我是否正确行事。我正在编写脚本来从数据库中提取并显示在它应该显示的html页面中,同时使用python文件来存储Django模板标记。我之前尝试从html文件中从数据库中提取数据但是因为我需要导入我的django模型库而无法在html上执行此操作。

我将代码分为两部分。执行查询的脚本位于标记为DatabaseQueryScript的标记模板中,如下所示:

@register.filter(name='PullEmployees')
  def PullEmployeesFromDatabase():
    AllEmployees = Profile.objects.all()
    return AllEmployees

然后我在html文件中调用该函数

{% load DatabaseQueryScript %}
{%for employee in PullEmployees%}
 ```printing data to a table on screen```
{%endfor%}

我希望能够在打开页面时看到桌面上的员工列表,但是在我执行查询之前,我在添加的标题旁边的表上没有任何内容。

django django-templates django-database
2个回答
1
投票

不幸的是,您似乎误解了如何使用Django模板过滤器。过滤器是您用来修改对象或与对象交互的东西。

如果你看看现有的内置过滤器,你可以找到multiple examples

EG

{{value|capfirst}}  # Converts a string stored in value, to be capitalized.

在您的特定情况下,您可能只想在模板上下文中添加数据库项列表。有多种方法可以执行此操作,具体取决于您是使用功能视图还是基于类的视图。

当您最终在上下文中定义变量时,您可以执行以下操作(其中object_list是上下文变量的示例名称)。

{% for obj in object_list %}

基于类的列表视图

from django.views.generic import ListView
class EmployeeListView(ListView):
    model = Employee
    template = "/mytemplate.html"

在这种情况下,ListView会自动将所有员工添加到名为object_list的模板变量中。

覆盖get_context_data

如果您没有使用ListView或者不想依赖创建对象列表的继承自动化,则可以在通用视图中覆盖get_context_data()方法。

from django.views.generic import TemplateView
class EmployeeView(TemplateView):
    template = "/mytemplate.html"

    def get_context_data(self):
        context = super().get_context_data()
        context["employee_list"] = self.get_queryset()
        return context

    def get_queryset(self):
        return Profile.objects.all()

使用功能视图

在功能视图的情况下,您只需将上下文作为kwarg传递给渲染函数。

def employee_view(request):
    return render(request, '/mytemplate.html', {'employee_list': get_queryset()})

def get_queryset():
    return Profile.objects.all()

1
投票

您不应该在模板过滤器或模板标签中执行此操作。它们用于修改模板的行为,或者对已传递给模板的数据进行更改。

您需要在视图中查询数据库。您可以使用适当的基于类的通用视图,在本例中为ListView,也可以将其添加到您的上下文中。

像这样使用ListView:

from django.views.generic.list import ListView

class ListAllEmployees(ListView):
  model = Profile

然后在您的模板中,您可以使用{% for profile in object_list %}迭代所有“配置文件”。

或者你可以添加你的上下文,将其传递给模板:

from django.views.generic import TemplateView

class ListAllEmployees(TemplateView):
  def get_context_data(self):
    ctx = super().get_context_data()
    ctx['profiles'] = Profile.objects.all()
    return ctx

然后你可以在模板中迭代它,如:{% for profile in profiles %}

© www.soinside.com 2019 - 2024. All rights reserved.