You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中调用模型方法并在模板中正确展示结果?

问题分析与解决方案

你遇到的核心问题是没有正确调用实例方法,同时模板的渲染逻辑也不符合数据类型的预期,以下是具体修正方案:

错误点拆解

  1. 视图中直接引用User.get_full_name,这是类的方法对象,而非通过用户实例调用后的返回值,也没有加括号执行方法。
  2. 模板中用{% for %}循环单个字符串(如果正确调用后得到的是单个用户全名),会导致字符串被拆分为单个字符遍历,不符合需求。

方案1:展示当前登录用户的全名

修正后的视图代码(views.py)

from django.shortcuts import render
from django.contrib.auth.decorators import login_required

# 需登录才能访问的视图,根据需求决定是否保留装饰器
@login_required
def about_us(request):
    # 获取当前登录的用户实例
    current_user = request.user
    # 调用实例方法get_full_name(),拿到返回的全名字符串
    fullname = current_user.get_full_name()
    context = {
        'fullname': fullname
    }
    return render(request, 'about_us.html', context=context)

修正后的模板代码(about_us.html)

<div class="container">
    <div class="d-flex flex-wrap justify-content-around">
        <p>{{ fullname }}</p>
    </div>
</div>

方案2:展示所有用户的全名列表

修正后的视图代码(views.py)

from django.shortcuts import render
from accounts.models import User

def about_us(request):
    # 从数据库获取所有用户实例
    all_users = User.objects.all()
    # 遍历用户实例,收集每个用户的全名
    full_names = [user.get_full_name() for user in all_users]
    context = {
        'full_names': full_names
    }
    return render(request, 'about_us.html', context=context)

修正后的模板代码(about_us.html)

<div class="container">
    <div class="d-flex flex-wrap justify-content-around">
        {% for name in full_names %}
        <p>{{ name }}</p>
        {% endfor %}
    </div>
</div>

内容的提问来源于stack exchange,提问作者HesamHashemi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:25:24