python - 在模板文件中调用模型方法
问题描述
我正在学习使用 django 创建一个博客网站。在模板文件中调用模型方法时遇到问题。该网站未在正文中显示内容。当我使用 article.body 时它工作正常,但当我使用 article.snippet 时它不工作。
模型.py 文件:-
...
from django.db import models
class Article(models.Model):
title = models.CharField(max_length = 100)
slug = models.SlugField()
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def snippet(self):
return self.body[:50]
...
article_list.html 文件:-
...
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Articles</title>
</head>
<body>
<h1>Articles List</h1>
<div class="articles">
{% for article in articles %}
<div class="article">
<h2><a href="">{{article.title}}</a></h2>
<p>{{article.body.snippet}}</p>
<p>{{article.date}}</p>
</div>
{% endfor %}
</div>
</body>
</html>
...
views.py 文件:-
...
from django.shortcuts import render
from django.http import HttpResponse
from .models import Article
def articles_list(request):
articles = Article.objects.all()
return render(request, 'articles/articles_list.html', {'articles': articles})
...
代码中没有显示错误,但 body 标签内仍然没有输出。
解决方案
你可以打电话
<p>{{article.snippet}}</p>
代替:
<p>{{article.body.snippet}}</p>
因为snippet是同模型中的方法所以可以直接调用,body不是ForeignKey
推荐阅读
- angular10 - Angular 10 通过 Await 获得 Web 服务状态?
- python - /model/train http API 在 json 中提供“nlu”数据时出现 500 错误
- python - 熊猫数据框中文本列中单词的频率计数并将其存储在其他列中
- compiler-errors - 编译内核问题
- c# - Dsharpplus 不响应命令
- c++ - C++——更新地图内的容器
- r - 构建一个函数,用R中的引号计算一个带有动态变量的值
- javascript - 当用户在全日历中选择时间时,取消选择全日历时出错
- python - 如何在if语句python中检查可变长度列表的元素
- c++ - 我用[]方法赋值,通过std::cout可以打印出数据,但是为什么size()返回0呢?