[Django]-How to access context from a custom django-admin command?

2👍

The Django test runner DiscoverRunner (and pytest’s auto-use fixture django_test_environment) calls setup_test_environment, which replaces Django Template._render. instrumented_test_render sends the template_rendered signal that the Django test Client connects to to populate data, from which it then sets response.context.

You can do the same in your custom management command:

from django.template import Template
from django.test.utils import instrumented_test_render

Template._render = instrumented_test_render

If you want to include all other patches used in tests, you can call setup_test_environment:

from django.test.utils import setup_test_environment

setup_test_environment()

Among other things, setup_test_environment replaces settings.EMAIL_BACKEND:

settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"

...

mail.outbox = []
👤aaron

Leave a comment