【发布时间】: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