在Django中全局存储错误代码和消息 [英] Storing error codes and messages globally in Django

查看:412
本文介绍了在Django中全局存储错误代码和消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django应用程序,当出现一些用户错误(即URL不存在或没有权限)时,它将执行 messages.add_message 。该消息包含指向 / error /< id> 上的错误说明的链接。如果我想重新使用错误ID和消息,我该怎么办?我正在想这样:



errors = {1:错误信息为错误ID 1,2:错误信息为错误ID 2}



我可以在哪里存储这样的字典,以便我可以在我的所有观点访问它?

解决方案

您应该创建一个视图,映射到 url ,如误差/< ID> 。然后在视图内有字典 errors = {1:错误信息为错误ID 1,2:错误信息为错误ID 2} 或者在一个文件称为 error_codes.py 并将其导入到您的 views.py 中。然后简单地解析 url 中传递的< id> 并返回一个模板正确的错误代码



为确保此字典的错误代码可用于所有请求,请使用写入自定义 Django Middleware 。执行 process_template_response(self,request,response),并通过添加来更改 response.context_data error_code_dictionary 。将确保每个响应都有在模板和其他地方呈现的http响应中的错误字典。


I have a Django app which when presented with some user error (i.e URL does not exist or no permissions), it will do messages.add_message. The message contains a link to an explanation of the error at /error/<id>. If I want to re-use the error id and message, how do I do it? I was thinking something like this:

errors = {1 : "Error message for error id 1", 2 : "Error message for error id 2"}

Where could I store such a dictionary so that I can access it in all of my views?

解决方案

You should create a view that maps to a url like /error/<id>. Then inside the view have the dictionary errors = {1 : "Error message for error id 1", 2 : "Error message for error id 2"} or alternatively inside a file called error_codes.py and import it into your views.py . Then simply parse the <id> passed in the url and return a template with the correct error code.

To ensure that this dictionary of error codes is available across all your requests, use write custom Django Middleware. Implement process_template_response(self, request, response) and alter the response.context_data by adding your error_code_dictionary to it. Will ensure that every response has the error dictionary available across your http responses rendered in templates and elsewhere.

这篇关于在Django中全局存储错误代码和消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆