【问题标题】:How do you pass model data to a template using Django?如何使用 Django 将模型数据传递给模板?
【发布时间】:2020-04-01 13:59:13
【问题描述】:

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

urls.py

from django.urls import path
from app import views

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

models.py

from django.db import models

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

views.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。最终我想检索几条记录并能够通过它们增加,但是我目前只是想让一个工作。我也尝试过使用 url 中的主键使用 DetailView,但是我不断收到错误,因此提供的示例代码似乎是我最接近目标的尝试。

【问题讨论】:

  • self.model 是模型类,你需要它的一个实例。

标签: python django django-templates


【解决方案1】:

您需要传递 model instances/queryset 而不是 cmets 中提到的 model class

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

【讨论】:

  • 您的解决方案返回“MyModel 匹配查询不存在”,尽管确认存在具有相应 RegNumber/pk 值的记录。
【解决方案2】:

这是一种非常简单的方法来满足您的需要。

views.py


from django.shortcuts import render
from .models import MyModel

def review_view(request, *args, **kwargs):

    # Getting all the stuff from database
    query_results = MyModel.objects.all();

    # Creating a dictionary to pass as an argument
    context = { 'query_results' : query_results }

    # Returning the rendered html
    return render(request, "review.html", context)

models.py :在这里,请确保您编写的是 models.Model 而不是 models.model

from django.db import models

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

urls.py

from django.urls import path
from app.views import review_view

urlpatterns = [
    path('review/', review_view , name='review')
]

文件review.html。确保在 settings.py 中为模板指定正确的 DIR 以避免模板未找到错误

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>

<body>

        {% for item in query_results %}
           <h1>{{ item.RegNumber }}</h1>
           <p>{{ item.Description }}</p>
        {% endfor %}

</body>
</html>

【讨论】:

  • 虽然基于函数的视图更容易理解(imo),但问题是关于基于类的视图。也许您找到了原始问题的解决方案。提出问题的人可能会出于某种原因试图避免基于功能的视图...
  • 我正在尝试使用基于类的视图,因为我相信它对我正在处理的特定应用程序更有意义。也就是说,我愿意接受任何能够实现从我的数据库中检索数据并将其传递给我的模板的目标。我尝试实施此解决方案并没有收到错误,但是传递给我的模板的是“”。
猜你喜欢
  • 2012-10-09
  • 2016-11-17
  • 1970-01-01
  • 2017-12-31
  • 2015-10-27
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多