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

解决Django报错并将grouping.py算法输出展示到Web页面

问题解决步骤

1. 修复URL配置的views导入错误

你的urls.py直接使用import views会导致导入歧义,Django无法定位到当前app的views模块。修改为相对导入:

# academic_balancing/urls.py
from django.urls import path
from . import views  # 导入当前app下的views模块

urlpatterns = [
    path('', views.algorithm_output, name='algorithm_output'),
]

2. 修复views中的函数调用逻辑

你在views.py中仅将函数对象赋值给output,并未实际调用函数获取结果,需要添加括号执行函数:

# academic_balancing/views.py
from django.shortcuts import render
from grouping import form_groups

def algorithm_output(request):
    # 调用算法函数获取输出结果(若函数需参数,需传入对应值)
    output = form_groups()
    # 将结果传递给模板
    return render(request, 'academic_balancing/academic.html', {'output': output})

3. 确保grouping.py的位置合规

将grouping.py放置在academic_balancingapp目录下(与views.py、urls.py同级),这样from grouping import form_groups才能正确导入。若文件在项目根目录,需调整导入语句为:

from ..grouping import form_groups

更推荐直接将文件移至app目录,符合Django项目结构规范。

4. 优化模板展示(可选)

若form_groups返回列表、字典等复杂结构,直接用{{output}}展示可读性差,可根据数据类型调整模板:

列表数据展示示例

<!-- academic_balancing/templates/academic_balancing/academic.html -->
<!DOCTYPE html>
<html>
  <body>
    <h2>算法输出结果</h2>
    <ul>
        {% for item in output %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
  </body>  
</html>

字典数据展示示例

<!-- academic_balancing/templates/academic_balancing/academic.html -->
<!DOCTYPE html>
<html>
  <body>
    <h2>算法输出结果</h2>
    {% for key, value in output.items %}
        <p><strong>{{ key }}:</strong> {{ value }}</p>
    {% endfor %}
  </body>  
</html>

5. 测试运行

完成修改后,在项目根目录执行命令启动服务:

python manage.py runserver

访问对应URL即可查看算法输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 02:26:01