繁体   English   中英

如何使用 Django 将模型数据传递给模板?

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

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

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

一个非常简单的方法来做你需要的就是这个。

视图.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)

网址.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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM