前提・実現したいこと
下記のコード tests.py と models.pyを用意してコマンドプロントからpython tests.pyを実行すると以下のようなエラーが出てしまいます。
しかし試しにview.pyに以下のようなコードを作成し、コマンドプロントから manage.py runserverを実行し tes2.htmlテンプレートを利用したweb画面のボタンから実行してみた場合、正常に処理できました。
どうして test.pyからはデータベースを扱うことができないのでしょうか?
test.pyからテスト用の埋め込みsqlを作成し、サーバーをいちいち稼働することなく論理エラーや文法エラーが出るか試したいので,ご教授お願いいたします。
発生している問題・エラーメッセージ
Traceback (most recent call last): File "tests.py", line 2, in <module> import models File "C:\Python\mysite\myapp1\models.py", line 50, in <module> class Sqltes(models.Model): File "C:\Python\env1\lib\site-packages\django\db\models\base.py", line 87, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Python\env1\lib\site-packages\django\apps\registry.py", line 249, in get_containing_app_config self.check_apps_ready() File "C:\Python\env1\lib\site-packages\django\apps\registry.py", line 131, in check_apps_ready settings.INSTALLED_APPS File "C:\Python\env1\lib\site-packages\django\conf\__init__.py", line 57, in __getattr__ self._setup(name) File "C:\Python\env1\lib\site-packages\django\conf\__init__.py", line 42, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
該当のソースコード
Django
1# tests.py 2 3import models 4 5b = Sqltes(id=4, name="new name4", testext="new text4" ) 6b.save()
Django
1# models.py 2 3import datetime 4 5from django.db import models 6from django.utils import timezone 7 8class Sqltes(models.Model): 9 id = models.IntegerField(primary_key=True) 10 name = models.CharField(max_length=255) 11 testext = models.CharField(max_length=255, blank=True, null=True) 12 13 class Meta: 14 managed = False 15 db_table = 'sqltes' 16
Django
1# views.py 2 3from django.http import HttpResponse 4from django.shortcuts import render 5from . import forms 6 7from .forms import MyForm 8from .models import * 9 10def tes_template(request): 11 #変数の初期数値は設定しなければならない 12 tes3 = "" 13 if request.method == 'POST': 14 b = Sqltes(id=4, name="new name4", testext="new text4") 15 b.save() 16 b = Sqltes.objects.get(pk=4) 17 tes3 = b.name 18 19 myapp_data = { 20 "tes1" : tes3, 21 } 22 return render(request, 'tes2.html' , myapp_data) 23
html
1# tes.html 2 3<!DOCTYPE html> 4<html lang="ja" dir="ltr"> 5 <head> 6 <meta charset="utf-8"> 7 <title></title> 8 <!-- UIkit CSS --> 9 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.25/css/uikit.min.css" /> 10 11 <!-- jQuery is required --> 12 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 13 14 <!-- UIkit JS --> 15 <script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.25/js/uikit.min.js"></script> 16 <script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.25/js/uikit-icons.min.js"></script> 17 </head> 18 <body> 19 <form class="" action="" method="post"> 20 {% csrf_token %} {# ← post を使う場合のおまじない#} 21 22 <input class="uk-input" type="text" name="tes" value=""> 23 <input class="uk-text-large" type="submit" name="button" value="送 信"> 24 25 </form> 26 27 </body> 28</html>
Django
1""" 2Django settings for mysite project. 3 4Generated by 'django-admin startproject' using Django 2.1.5. 5 6For more information on this file, see 7https://docs.djangoproject.com/en/2.1/topics/settings/ 8 9For the full list of settings and their values, see 10https://docs.djangoproject.com/en/2.1/ref/settings/ 11""" 12 13import os 14 15# Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 18 19# Quick-start development settings - unsuitable for production 20# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ 21 22# SECURITY WARNING: keep the secret key used in production secret! 23SECRET_KEY = 'r4+r_%h^q1y=oclmulfbzp=%0(4batna5o%&s!$n)c^4%-ur4h' 24 25# SECURITY WARNING: don't run with debug turned on in production! 26DEBUG = True 27 28ALLOWED_HOSTS = [] 29 30 31# Application definition 32 33INSTALLED_APPS = [ 34 'django.contrib.admin', 35 'django.contrib.auth', 36 'django.contrib.contenttypes', 37 'django.contrib.sessions', 38 'django.contrib.messages', 39 'django.contrib.staticfiles', 40 'myapp1', 41 'crud', #追加分 42 43] 44 45MIDDLEWARE = [ 46 'django.middleware.security.SecurityMiddleware', 47 'django.contrib.sessions.middleware.SessionMiddleware', 48 'django.middleware.common.CommonMiddleware', 49 'django.middleware.csrf.CsrfViewMiddleware', 50 'django.contrib.auth.middleware.AuthenticationMiddleware', 51 'django.contrib.messages.middleware.MessageMiddleware', 52 'django.middleware.clickjacking.XFrameOptionsMiddleware', 53] 54 55ROOT_URLCONF = 'mysite.urls' 56 57TEMPLATES = [ 58 { 59 'BACKEND': 'django.template.backends.django.DjangoTemplates', 60 'DIRS': [ 61 os.path.join(BASE_DIR, 'templates'), 62 ], 63 'APP_DIRS': True, 64 'OPTIONS': { 65 'context_processors': [ 66 'django.template.context_processors.debug', 67 'django.template.context_processors.request', 68 'django.contrib.auth.context_processors.auth', 69 'django.contrib.messages.context_processors.messages', 70 ], 71 }, 72 }, 73] 74 75WSGI_APPLICATION = 'mysite.wsgi.application' 76 77 78# Database 79# https://docs.djangoproject.com/en/2.1/ref/settings/#databases 80 81DATABASES = { 82 'default': { 83 'ENGINE': 'django.db.backends.mysql', 84 'NAME': 'test', #データベース名 85 'USER': 'mysql', #ユーザー名 86 'PASSWORD': 'パスワード', #パスワード 87 'HOST': 'IPアドレス', #PCのIPアドレス(デフォルトは localhost ) 88 'PORT': 'ポート番号', #ポート番号 89 } 90} 91 92 93# Password validation 94# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 95 96AUTH_PASSWORD_VALIDATORS = [ 97 { 98 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 99 }, 100 { 101 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 102 }, 103 { 104 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 105 }, 106 { 107 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 108 }, 109] 110 111 112# Internationalization 113# https://docs.djangoproject.com/en/2.1/topics/i18n/ 114 115LANGUAGE_CODE = 'en-us' 116 117TIME_ZONE = 'Asia/Tokyo' 118 119USE_I18N = True 120 121USE_L10N = True 122 123USE_TZ = True 124 125 126# Static files (CSS, JavaScript, Images) 127# https://docs.djangoproject.com/en/2.1/howto/static-files/ 128 129STATIC_URL = '/static/' 130```Django 131 132### 試したこと 133 134ここに問題に対して試したことを記載してください。 135 136Command==0.1.0 137Django==2.1.5 138django-uikit-admin==0.1.1 139django-uikit-editor==0.0.1 140pytz==2018.9 141Python 3.6.5