Django 1.8 official document translation: 6-6-5 error report


Error report

When you run a public site, you should always shut it downDEBUGset up. This will make your server run faster and prevent malicious users from seeing some of the application details displayed by the error page.

However, running onDEBUGbyFalseIn this case, you don’t see the errors generated by your site – everyone can only see the public error page. You need to track errors on the deployed site, so you can configure Django to generate reports with error details.

Report mail

Server error

DEBUGbyFalseWhenever the code generates an unhandled exception and a server internal error (HTTP status code 500), Django will give theADMINSUsers in settings send mail. This will provide the administrator with timely notification of any errors.  ADMINSYou’ll get a description of the error, a complete Python traceback, as well as the HTTP request and the details that caused the error.

be careful

In order to send mail, Django needs some settings to tell it how to connect to the mail server. At least, you need to specifyEMAIL_HOST, may needEMAIL_HOST_USERandEMAIL_HOST_PASSWORD, although the other settings you need may also depend on the configuration of your mail server. For a complete list of email related settings, see_ Django settings document_

Django usually starts fromComplete tracebackTraceback frameEach local variable of, andHttpRequestOf_ Properties_

However, sometimes specific message types are too sensitive to track messages, such as the user’s password or credit card number. So Django provides a set of function decorators to help you control what you need in the production environment (i.eDEBUGbyFalseMessage filtered in the error report in:sensitive_variables()andsensitive_post_parameters()


If a function (view or regular callback) in your code uses local variables that may contain sensitive information, you may need to usesensitive_variablesDecorator to prevent error reports from containing the values of these variables.

from django.views.decorators.debug import sensitive_variables

@sensitive_variables('user', 'pw', 'cc')
def process_info(user):
    pw = user.pass_word
    cc = user.credit_card_number
    name =

In the example above,user, pwandccThe value of the variable is hidden in the error report and an asterisk (< cite > 0) is used**< / cite >), thoughnameThe value of the variable is exposed.

To hide all local variables of a function in an error report in order, do notsensitive_variablesThe decorator provides any parameters:

def my_function():

When using multiple decorators

If you want to hide the variable is also a function parameter (for example, in the following example)user)And the decorated function has multiple decorators, you need to make sure that@sensitive_variablesAt the top of the decorator chain. This method also hides function parameters, although it is passed through other decorators:

@sensitive_variables('user', 'pw', 'cc')
def process_info(user):


If a view in your code receives a view that may have sensitive information withPost parametersOfHttpRequestObject that you may need to usesensitive_post_parametersDecorator to prevent error reports from containing the values of these parameters.

from django.views.decorators.debug import sensitive_post_parameters

@sensitive_post_parameters('pass_word', 'credit_card_number')
def record_user_profile(request):

In the example above,pass_wordandcredit_card_numberThe value of the post parameter is hidden in the error report and an asterisk (< cite > 0) is used**< / cite >), thoughnameThe value of the variable is exposed.

To hide all the post parameters of a request in order in the error report, do notsensitive_post_parametersThe decorator provides any parameters:

def my_view(request):

All post parameters are filtered out in orderdjango.contrib.auth.viewsError reporting for views(login, password_reset_confirm, password_change, add_viewandauthInuser_change_password)To prevent the disclosure of sensitive information such as user passwords.

Custom error reporting

Allsensitive_variables()Andsensitive_post_parameters()Annotate the decorated function with the name of sensitive variable, and annotate the function with the name of post sensitive parameterHttpRequestObject so that sensitive information in the report can be filtered out later when an error occurs. Django’s default error packet filterdjango.views.debug.SafeExceptionReporterFilterWill complete the actual filtering operation.
When an error report is generated, the filter uses the decorator’s annotation to replace the corresponding value with an asterisk (< cite >)**</cite>) 。 If you want to override or customize this default property for your entire site, you need to define your own filter class andDEFAULT_EXCEPTION_REPORTER_FILTERSet to let Django use it.


You may also be able to control in a more subtle way which filters are used in the provided view by settingHttpRequestOfexception_reporter_filterProperty.

def my_view(request):
    if request.user.is_authenticated():
        request.exception_reporter_filter = CustomExceptionReporterFilter()

Your custom filter class needs to inherit fromdjango.views.debug.SafeExceptionReporterFilter, and you may need to override the following methods:

_class _SafeExceptionReporterFilter[source]


If the filter operated in other methods has been activated, return toTrue. IfDEBUGbyFalse, usually the filter is active.


Returns the representation string of the request object, that is, the value that would be returned by repr(request), except it uses the filtered dictionary of POST parameters as determined by SafeExceptionReporterFilter.get_post_parameters().


Returns the filtered post parameter dictionary. Usually, the values of sensitive parameters are marked with an asterisk (< cite >)**< / cite >).

SafeExceptionReporterFilter.`get_traceback_frame_variables`(_request_, _tb_frame_)[source]

Returns the dictionary of the local variables of the provided traceback frame after filtering. Usually, the value of sensitive variable is marked with an asterisk (< cite >)**< / cite >).

See also

You can also write custom_exception middleware_To create a custom error report. If you write a custom error handler to simulate Django’s built-in error handler, onlyDEBUGbyFalseIt’s a good idea to report or record errors when you do.

translator:Django document collaborative translation teamOriginal text:Tracking code errors by email

This paper is based onCC BY-NC-SA 3.0Please keep the author’s signature and the source of the article.

Django document collaborative translation teamWe are short of staff. Interested friends can join us. It is totally public welfare. Communication group: 467338606.