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

Django项目对接Mayan EDMS REST API问题求助

问题分析与修复方案

原代码核心问题

  1. Django视图返回值错误:视图函数必须返回HttpResponse或其子类(如JsonResponse、TemplateResponse),直接返回字典会触发Django运行错误。
  2. 缺少API认证:Mayan EDMS的REST API默认要求Token认证,未携带认证信息会返回401未授权状态。
  3. 未处理API分页:Mayan的文档接口默认分页返回数据,直接取第一页结果会遗漏大量文档。
  4. 未实现界面渲染:原代码仅返回数据,未将数据传递给Django模板完成前端展示。

修复后的完整实现

1. 先配置Mayan API Token

在Mayan EDMS后台生成API Token:

  • 进入Mayan用户管理页面,找到对应操作用户,生成并复制API Token。
  • 在Django项目的settings.py中添加全局配置:
MAYAN_EDMS_API_URL = "http://localhost/api/v4/"
MAYAN_EDMS_API_TOKEN = "你的Mayan API Token"

2. 修复后的视图函数

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
import requests
from django.conf import settings

@login_required
def f_facturaspendientes(request):
    url = f"{settings.MAYAN_EDMS_API_URL}documents/"
    headers = {"Authorization": f"Token {settings.MAYAN_EDMS_API_TOKEN}"}
    all_documents = []
    error_msg = None

    try:
        # 循环获取所有分页的文档数据
        while url:
            response = requests.get(url, headers=headers)
            if response.status_code == 200:
                data = response.json()
                all_documents.extend(data["results"])
                # 更新下一页请求地址
                url = data.get("next")
            else:
                error_msg = f"API请求失败,状态码: {response.status_code}"
                break
    except requests.exceptions.RequestException as e:
        error_msg = f"请求异常: {str(e)}"

    # 渲染模板并传递数据到前端
    return render(request, 'documents/mayan_docs.html', {
        'documents': all_documents,
        'error': error_msg
    })

3. 对应的Django模板(templates/documents/mayan_docs.html)

<!DOCTYPE html>
<html>
<head>
    <title>Mayan文档列表</title>
</head>
<body>
    <h1>Mayan EDMS 文档列表</h1>
    {% if error %}
        <p style="color: #dc3545;">{{ error }}</p>
    {% endif %}
    <div class="document-list">
        {% for doc in documents %}
            <div class="document-item">
                <h3>{{ doc.label }}</h3>
                <p>文档ID: {{ doc.id }}</p>
                <p>创建时间: {{ doc.date_created }}</p>
                <a href="{{ doc.download_url }}" target="_blank" class="download-link">下载文档</a>
            </div>
        {% empty %}
            <p>暂无文档数据</p>
        {% endfor %}
    </div>
</body>
<style>
.document-item {border: 1px solid #eee; padding: 10px; margin: 10px 0; border-radius: 4px;}
.download-link {color: #0d6efd; text-decoration: none;}
</style>
</html>

关键修复说明

  • 认证处理:通过请求头携带Mayan的API Token,确保请求被服务器授权。
  • 分页遍历:循环调用API的分页接口,收集所有文档数据,避免数据遗漏。
  • 规范视图返回:使用render方法返回模板页面,将文档数据和错误信息传递到前端展示。
  • 错误友好提示:将API请求过程中的错误信息传递到模板,在页面中直观展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 12:23:29