def _configure_django(self, **kw):
        from django.conf import settings, global_settings
        self.settings = settings
        if settings.configured:
            return

        self.APP_DIR, app_filename = os.path.split(
            os.path.realpath(inspect.stack()[2][1])
        )

        DEBUG = kw.get("DEBUG", False)
        md = {}
        dp = {}

        for k, v in kw.items():
            if isinstance(v, E):
                md[k] = v.value
                setattr(global_esettings, k, v.value)
            if isinstance(v, DSetting):
                dp[k] = v

        for k, v in md.items():
            kw[k] = v

        for k, v in dp.items():
            if DEBUG:
                if v.dvalue is not NotSet:
                    kw[k] = v.dvalue
            else:
                if v.pvalue is not NotSet:
                    kw[k] = v.pvalue

        del md
        del dp

        def do_dp(key):
            if key not in kw:
                return
            old = kw[key]
            kw[key] = []
            for value in old:
                if DEBUG:
                    if value.startswith("prod:"):
                        continue
                    kw[key].append(value.replace("debug:", ""))
                else:
                    if value.startswith("debug:"):
                        continue
                    kw[key].append(value.replace("prod:", ""))

        s_found = 0
        sd = {}
        for k, v in kw.items():
            if isinstance(v, MirrorSetting):
                s_found += 1
                if s_found > MirrorSetting.count:
                    raise ImproperlyConfiguredError
                sd[k] = v

        if MirrorSetting.count > s_found:
            raise ImproperlyConfiguredError

        for k, v in sd.items():
            kw[k] = kw[v.name]

        del sd
        del s_found

        do_dp("MIDDLEWARE_CLASSES")
        do_dp("INSTALLED_APPS")
        do_dp("TEMPLATE_CONTEXT_PROCESSORS")

        if "debug" in kw:
            db = kw.pop("debug")
            if DEBUG:
                kw.update(db)

        if "regexers" in kw:
            self.update_regexers(kw.pop("regexers"))

        self.mounts = kw.pop("mounts", {})

        if not kw.get("dont_configure", False):
            kw["ROOT_URLCONF"] = kw.get("ROOT_URLCONF", "importd.urlconf")
            if "TEMPLATE_DIRS" not in kw:
                kw["TEMPLATE_DIRS"] = (self.dotslash("templates"), )
            if "STATIC_URL" not in kw:
                kw["STATIC_URL"] = "/static/"
            if "STATIC_ROOT" not in kw:
                kw["STATIC_ROOT"] = self.dotslash("staticfiles")
            if "STATICFILES_DIRS" not in kw:
                kw["STATICFILES_DIRS"] = [self.dotslash("static")]
            if "MEDIA_URL" not in kw:
                kw["MEDIA_URL"] = "/static/media/"
            if "lr" in kw:
                self.lr = kw.pop("lr")
            if "db" in kw:
                if isinstance(kw["db"], basestring):
                    kw["DATABASES"] = {
                        "default": dj_database_url.parse(kw.pop("db"))
                    }
                else:
                    db = kw.pop("db")
                    default = dj_database_url.parse(db[0])
                    default.update(db[1])
                    kw["DATABASES"] = dict(default=default)
            if "DATABASES" not in kw:
                kw["DATABASES"] = {
                    "default": {
                        'ENGINE': "django.db.backends.sqlite3",
                        'NAME': self.dotslash("db.sqlite")
                    }
                }

            self.smart_return = False
            if kw.pop("SMART_RETURN", True):
                self.smart_return = True
                if "MIDDLEWARE_CLASSES" not in kw:
                    kw["MIDDLEWARE_CLASSES"] = (
                        global_settings.MIDDLEWARE_CLASSES
                    )
                kw["MIDDLEWARE_CLASSES"] = list(kw["MIDDLEWARE_CLASSES"])
                kw["MIDDLEWARE_CLASSES"].append(
                    "importd.SmartReturnMiddleware"
                )

            installed = list(kw.setdefault("INSTALLED_APPS", []))

            admin_url = kw.pop("admin", "^admin/")

            if admin_url:
                if "django.contrib.auth" not in installed:
                    installed.append("django.contrib.auth")
                if "django.contrib.contenttypes" not in installed:
                    installed.append("django.contrib.contenttypes")
                if "django.contrib.auth" not in installed:
                    installed.append("django.contrib.auth")
                if "django.contrib.messages" not in installed:
                    installed.append("django.contrib.messages")
                if "django.contrib.sessions" not in installed:
                    installed.append("django.contrib.sessions")
                    # check session middleware installed
                    # https://docs.djangoproject.com/en/1.7/topics/http/sessions/#enabling-sessions
                    last_position = len(kw["MIDDLEWARE_CLASSES"])
                    kw["MIDDLEWARE_CLASSES"] = list(kw["MIDDLEWARE_CLASSES"])
                    kw["MIDDLEWARE_CLASSES"].insert(
                        last_position,
                        "django.contrib.sessions.middleware.SessionMiddleware"
                    )
                if "django.contrib.admin" not in installed:
                    installed.append("django.contrib.admin")
                    kw["MIDDLEWARE_CLASSES"].append(
                        "django.contrib.auth.middleware"
                        ".AuthenticationMiddleware"
                    )
                if "django.contrib.humanize" not in installed:
                    installed.append("django.contrib.humanize")
                if "django.contrib.staticfiles" not in installed:
                    installed.append("django.contrib.staticfiles")
                if "debug_toolbar" not in installed and debug_toolbar:
                    installed.append("debug_toolbar")
                    if 'INTERNAL_IPS' not in kw:
                        kw['INTERNAL_IPS'] = ('127.0.0.1', '0.0.0.0')
                    kw['MIDDLEWARE_CLASSES'].insert(
                        1,
                        'debug_toolbar.middleware.DebugToolbarMiddleware')
                    kw['DEBUG_TOOLBAR_PANELS'] = (
                        'debug_toolbar.panels.versions.VersionsPanel',
                        'debug_toolbar.panels.timer.TimerPanel',
                        'debug_toolbar.panels.settings.SettingsPanel',
                        'debug_toolbar.panels.headers.HeadersPanel',
                        'debug_toolbar.panels.request.RequestPanel',
                        'debug_toolbar.panels.sql.SQLPanel',
                        'debug_toolbar.panels.staticfiles.StaticFilesPanel',
                        'debug_toolbar.panels.templates.TemplatesPanel',
                        'debug_toolbar.panels.cache.CachePanel',
                        'debug_toolbar.panels.signals.SignalsPanel',
                        'debug_toolbar.panels.logging.LoggingPanel',
                        'debug_toolbar.panels.redirects.RedirectsPanel',
                    )
                    # This one gives 500 if its Enabled without previous syncdb
                    # 'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',

            kw['INSTALLED_APPS'] = installed

            if "DEBUG" not in kw:
                kw["DEBUG"] = kw["TEMPLATE_DEBUG"] = True
            if "APP_DIR" not in kw:
                kw["APP_DIR"] = self.APP_DIR
            if "SECRET_KEY" not in kw:
                kw["SECRET_KEY"] = self.get_secret_key()
            # admins and managers
            if "ADMINS" not in kw:
                kw["ADMINS"] = kw["MANAGERS"] = ((getuser(), ""), )
            autoimport = kw.pop("autoimport", True)

            kw["SETTINGS_MODULE"] = kw.get("SETTINGS_MODULE", "importd")

            settings.configure(**kw)
            if hasattr(django, "setup"):
                django.setup()

            self._import_django()

            from django.contrib.staticfiles.urls import staticfiles_urlpatterns
            urlpatterns = self.get_urlpatterns()
            urlpatterns += staticfiles_urlpatterns()

            if autoimport:
                # django depends on INSTALLED_APPS's model
                for app in settings.INSTALLED_APPS:
                    self._import_app_module("{}.admin", app)
                    self._import_app_module("{}.models", app)

            if admin_url:
                from django.contrib import admin
                try:
                    from django.conf.urls import include
                except ImportError:
                    from django.conf.urls.defaults import include  # lint:ok
                admin.autodiscover()
                self.add_view(admin_url, include(admin.site.urls))

            if autoimport:
                # import .views and .forms for each installed app
                for app in settings.INSTALLED_APPS:
                    self._import_app_module("{}.forms", app)
                    self._import_app_module("{}.views", app)
                    self._import_app_module("{}.signals", app)

        # import blueprints from config
        self.blueprints = kw.pop("blueprints", {})
        for namespace, meta in self.blueprints.items():
            if isinstance(meta, basestring):
                meta = {"blueprint": meta}

            mod_path, bp_name = meta["blueprint"].rsplit(".", 1)
            mod = importlib.import_module(mod_path)
            bp = getattr(mod, bp_name)

            self.register_blueprint(
                bp, url_prefix=meta.get("url_prefix", namespace + "/"),
                namespace=namespace, app_name=meta.get("app_name", ""))

        self._configured = True
Auto-Configure Django using arguments.
dataset/ETHPy150Open amitu/importd/importd/__init__.py/D._configure_django