How About Using MagicMock Instead of Defining Settings When You Want to Use Django Features (Such as Template Renderer)? → Incorrect

Django
2015-07-07 17:07 (9 years ago) ytyng

I was wrong.

from django.conf import settings
settings.configure()

It was as simple as calling settings.configure().

The following is irrelevant:


In a script unrelated to Django

t = Template(open(template_path).read())
c = Context({})
rendered = t.render(c)

I wanted to use the template renderer quickly like this

or use only single features of Django.

If you don't pay attention to PYTHONPATH or define the environment variable DJANGO_SETTINGS_MODULE,

django.core.exceptions.ImproperlyConfigured: Requested setting TEMPLATE_DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

you will get this error.

Ideally, it would be better to organize it into a Django management command and run it with ./manage.py hoge, but if you don't want to make it so formal, or if you want to do it outside of a Django project,

from unittest.mock import MagicMock
from django import conf
setattr(conf, 'settings', MagicMock())

how about monkey-patching settings with an instance of MagicMock like this?

If you do this, you can then

t = Template(open(template_path).read())
c = Context({})
rendered = t.render(c)

also execute this.

(Though you might say just use Jinja2)

Current rating: 3
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Comments

Archive

2025
2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011