首页 > 解决方案 > 在模板文件中调用模型方法

问题描述

我正在学习使用 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 标签内仍然没有输出。

标签: pythondjangodjango-modelsdjango-viewsdjango-templates

解决方案


你可以打电话

<p>{{article.snippet}}</p>

代替:

<p>{{article.body.snippet}}</p>

因为snippet是同模型中的方法所以可以直接调用,body不是ForeignKey


推荐阅读