---
slug: "Djangoの機能(テンプレートレンダラ)などを使いたいけどsettingsを定義したくない時、MagicMockを変わりに使うのはどうでしょう→間違ってた"
title: "How About Using MagicMock Instead of Defining Settings When You Want to Use Django Features (Such as Template Renderer)? → Incorrect"
description: "\n\nI was wrong."
url: "https://www.ytyng.com/en/blog/Djangoの機能(テンプレートレンダラ)などを使いたいけどsettingsを定義したくない時、MagicMockを変わりに使うのはどうでしょう→間違ってた"
publish_date: "2015-07-07T08:07:57Z"
created: "2015-07-07T08:07:57Z"
updated: "2026-02-27T10:43:23.308Z"
categories: ["Django"]
keywords: ""
featured_image_url: "https://media.ytyng.com/resize/20230812/204cc50e69d64bdd8cb9411875c49886.png.webp?width=768"
has_video: false
has_music: false
video_urls: []
music_urls: []
lang: "en"
---

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

<div class="document">

<p>I was wrong.</p>
<pre class="literal-block">from django.conf import settings
settings.configure()
</pre>
<p>It was as simple as calling settings.configure().</p>
<p>The following is irrelevant:</p>
<hr class="docutils"/>
<p>In a script unrelated to Django</p>
<pre class="literal-block">t = Template(open(template_path).read())
c = Context({})
rendered = t.render(c)
</pre>
<p>I wanted to use the template renderer quickly like this</p>
<p>or use only single features of Django.</p>
<p>If you don't pay attention to PYTHONPATH or define the environment variable DJANGO_SETTINGS_MODULE,</p>
<p>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.</p>
<p>you will get this error.</p>
<p>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,</p>
<pre class="literal-block">from unittest.mock import MagicMock
from django import conf
setattr(conf, 'settings', MagicMock())
</pre>
<p>how about monkey-patching settings with an instance of MagicMock like this?</p>
<p>If you do this, you can then</p>
<pre class="literal-block">t = Template(open(template_path).read())
c = Context({})
rendered = t.render(c)
</pre>
<p>also execute this.</p>
<p>(Though you might say just use Jinja2)</p>
</div>
