如何显示存储在 QuerySet object 中的模型的属性?
how can i display the properties of my models that are stored in the QuerySet object?
我的 Django 应用程序有一个简单的模型,我创建了 3 个实例,每个实例都有标题和描述属性,我如何使用这些属性在 html 模板中显示?
models.py:
from django.db import models
class Solution(models.Model):
title = models.CharField(max_length=200, help_text='Enter a title of solution')
description = models.TextField(max_length=1000, help_text='Enter a description of solution',)
def __str__(self):
return self.title
views.py:
from django.shortcuts import render
from .models import Solution
from django.views import generic
def index(request):
solutions = Solution.objects.all()
return render(request, "main/index.html", {'solutions': solutions})
我需要在文件中做这样的事情 html:
<div class="content">
<h3>{{ solution.title }}</h3>
如果您只需要第一个对象,那么您必须编辑您的查询,试试这样:
Views.py
from django.shortcuts import render
from .models import Solution
from django.views import generic
def index(request):
solutions = Solution.objects.first()
return render(request, "main/index.html", {'solutions': solutions})
模板
{{ solutions.title }}
如果您不想更改查询,也可以在模板中使用 this 来获取第一个对象:
{{ solutions|first }}
我的 Django 应用程序有一个简单的模型,我创建了 3 个实例,每个实例都有标题和描述属性,我如何使用这些属性在 html 模板中显示?
models.py:
from django.db import models
class Solution(models.Model):
title = models.CharField(max_length=200, help_text='Enter a title of solution')
description = models.TextField(max_length=1000, help_text='Enter a description of solution',)
def __str__(self):
return self.title
views.py:
from django.shortcuts import render
from .models import Solution
from django.views import generic
def index(request):
solutions = Solution.objects.all()
return render(request, "main/index.html", {'solutions': solutions})
我需要在文件中做这样的事情 html:
<div class="content">
<h3>{{ solution.title }}</h3>
如果您只需要第一个对象,那么您必须编辑您的查询,试试这样:
Views.py
from django.shortcuts import render
from .models import Solution
from django.views import generic
def index(request):
solutions = Solution.objects.first()
return render(request, "main/index.html", {'solutions': solutions})
模板
{{ solutions.title }}
如果您不想更改查询,也可以在模板中使用 this 来获取第一个对象:
{{ solutions|first }}