drf-yasg Swagger UI头部自定义:添加内容位置异常问题
替换drf-yasg Swagger UI默认头部的方法
你遇到的问题核心是:Swagger UI的默认头部由swagger-ui-bundle.js动态渲染生成,并非模板中的静态内容,所以直接在extra_body区块添加的header只会显示在Swagger UI容器上方,无法替换目标头部区域。以下是两种可行解决方案:
方法一:通过配置修改标题(简洁推荐)
在Django项目的settings.py中,通过SWAGGER_SETTINGS传递自定义配置,直接修改站点标题:
SWAGGER_SETTINGS = { # 保留现有其他配置 'SWAGGER_UI_SETTINGS': { 'customSiteTitle': '你的API文档标题', # 替换为自定义标题 } }
方法二:通过JavaScript完全自定义头部(含图标)
如果需要替换图标并自定义头部结构,在模板的extra_styles和extra_scripts区块添加代码,等待Swagger UI渲染完成后替换默认头部:
{% block extra_styles %} <style> /* 自定义头部样式 */ .swagger-ui .topbar .custom-header { display: flex; align-items: center; gap: 12px; padding: 0 24px; height: 60px; } .swagger-ui .topbar .custom-logo { height: 40px; width: auto; } .swagger-ui .topbar .custom-title { margin: 0; font-size: 1.6rem; color: #2c3e50; } </style> {% endblock %} {% block extra_scripts %} <script> document.addEventListener('DOMContentLoaded', function() { // 监听Swagger UI容器的DOM变化,等待头部生成 const observer = new MutationObserver((mutations) => { const defaultTopbar = document.querySelector('.swagger-ui .topbar'); if (defaultTopbar) { // 替换默认头部内容 defaultTopbar.innerHTML = ` <div class="custom-header"> <img src="{% static 'path/to/your-logo.png' %}" alt="自定义图标" class="custom-logo"> <h1 class="custom-title">你的自定义头部名称</h1> </div> `; observer.disconnect(); // 完成替换后停止监听 } }); // 监听swagger-ui容器的子元素变化 observer.observe(document.getElementById('swagger-ui'), { childList: true, subtree: true }); }); </script> {% endblock %}
- 替换
{% static 'path/to/your-logo.png' %}为自定义图标的实际路径 - 可调整CSS样式参数匹配需求
注意事项
- 自定义图标需放在Django静态文件目录,生产环境需运行
collectstatic命令 - 仅修改标题用方法一,复杂自定义用方法二
内容的提问来源于stack exchange,提问作者Marlon Bucalan
相关产品推荐
相关产品推荐

