首页 > 解决方案 > 如何使用 Django 将模型数据传递给模板?

问题描述

我正在尝试使用基于类的视图将数据从 Django 模型传递到 HTML 模板中。

网址.py

from django.urls import path
from app import views

urlpatterns = [
    path('review/', views.ReviewRecord.as_view(template_name='review.html'), name='review')
]

模型.py

from django.db import models

class MyModel(models.model):
    RegNumber = models.TextField(primary_key=True)
    Description = models.TextField(null=True)

视图.py

from app.models import MyModel
from django.views.generic import TemplateView

class ReviewRecord(TemplateView)
    template_name = 'review.html'
    model = myModel

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['description'] = self.model.description
        return context

html

<textarea readonly>{{ description }}</textarea>

上面的代码将以下内容插入到 html textarea 中:

<django.db.models.query_utils.DeferredAttribute object at 0x0000024C449B9F88>

我需要显示模型中存储的字段数据,而不是如上所述的对象数据。

我正在尝试基于模型中的字段创建查询集,例如,对于特定的 RegNumber。最终我想检索几条记录并能够通过它们增加,但是我目前只是想让一个工作。我也尝试使用 DetailView 使用 url 中的主键,但是我不断收到错误,因此提供的示例代码似乎是我最接近目标的尝试。

标签: pythondjangodjango-templates

解决方案


您需要传递模型实例/查询集而不是评论中提到的模型类

class ReviewRecord(TemplateView):
    template_name = 'review.html'
    model = Mymodel
    pk = 1

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # specfic instance description
        context['Description'] = Mymodel.objects.get(pk=self.pk).Description
        # all instances' descriptions
        context['all_descriptions'] = Mymodel.objects.values_list('Description', flat=True)
        # pass other variables
        context['other_var'] = 'other_var'
        return context

推荐阅读