Django类视图加载命名空间应用模板报TemplateDoesNotExist,函数视图正常
解决Django类视图找不到命名空间模板的问题
问题根源在于类视图的template_name未添加应用命名空间前缀,导致Django模板加载器无法定位到你放在users/templates/users/目录下的模板文件。
修复方法
直接修改UserSignupView中的template_name参数,补充应用命名空间前缀:
class UserSignupView(CreateView): model = CustomUser form_class = UserProfileSignupForm # 加上users/前缀,匹配模板路径users/templates/users/signup_form.html template_name = 'users/signup_form.html' def somefunction(self, **kwargs): ...
原因说明
- 函数视图中你使用
render(request, "users/test.html"),这个路径会让Django自动在所有已注册应用的templates目录下查找users/test.html,正好命中你放在users/templates/users/里的文件。 - 而你原本的类视图只写了
signup_form.html,Django会直接去各应用的templates根目录查找该文件,自然找不到你放在子目录中的模板,也就出现了报错里的那些无效查找路径。
修改后即可遵循Django的模板命名空间规范,无需移动模板文件就能正常运行。
内容的提问来源于stack exchange,提问作者user22002675
相关产品推荐
相关产品推荐

