python - 如何使用 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 中的主键,但是我不断收到错误,因此提供的示例代码似乎是我最接近目标的尝试。
解决方案
您需要传递模型实例/查询集而不是评论中提到的模型类
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
推荐阅读
- javascript - 如何正确使用 Promise 在函数末尾返回数组?
- amazon-ses - 无法使用亚马逊 ses 和烧瓶邮件通过 tls 发送电子邮件
- google-cloud-firestore - 如果我使用日期值,firestore orderBy 会起作用吗?
- php - 在 laravel 中使用 CKEditor 显示 textarea 内容
- python - 用 python 关闭 safari
- spring-security - 替换已弃用的 Spring Security JwtHelper
- xpath - IMPORTXML 导入的内容为空 - 请参阅演示表
- c# - Xero OAuth 2.0 API - c# dotnet core - 将附件上传到发票时未经授权 - 其他请求正常
- python - Python 速成课程 9-15 练习
- javascript - 在 Angular Material 树中实现拖放 - 当另一个节点悬停时嵌套节点