質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
Django

DjangoはPythonで書かれた、オープンソースウェブアプリケーションのフレームワークです。複雑なデータベースを扱うウェブサイトを開発する際に必要な労力を減らす為にデザインされました。

PostgreSQL

PostgreSQLはオープンソースのオブジェクトリレーショナルデータベース管理システムです。 Oracle Databaseで使われるPL/SQLを参考に実装されたビルトイン言語で、Windows、 Mac、Linux、UNIX、MSなどいくつものプラットフォームに対応しています。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

PyCharm

エディター・開発ツール

Q&A

0回答

1506閲覧

djangoの全プロジェクトテスト時のエラーについて

退会済みユーザー

退会済みユーザー

総合スコア0

Django

DjangoはPythonで書かれた、オープンソースウェブアプリケーションのフレームワークです。複雑なデータベースを扱うウェブサイトを開発する際に必要な労力を減らす為にデザインされました。

PostgreSQL

PostgreSQLはオープンソースのオブジェクトリレーショナルデータベース管理システムです。 Oracle Databaseで使われるPL/SQLを参考に実装されたビルトイン言語で、Windows、 Mac、Linux、UNIX、MSなどいくつものプラットフォームに対応しています。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

PyCharm

エディター・開発ツール

0グッド

0クリップ

投稿2021/09/10 15:37

編集2021/09/11 02:57

前提・実現したいこと

django初学者です。

「動かして学ぶ! Python Django開発入門」という書籍を見ながら、
djangoを使ってWEBアプリケーションを作成しようとしています。

各種WEBページとDBの設定等完了したつもりで、TestCaseクラスとSeleniumを使ったテストコードを作成して、
すべてのプロジェクトのテストを実施したのですが、以下の3件のエラーの修正箇所がわからず、お力添え頂けますでしょうか。

(仮想環境) 最上位のプロジェクトディレクトリ>python manage.py test
System check identified no issues (0 silenced).

DevTools listening on ws://127.0.0.1:53911/devtools/browser/5677e94c-b138-4742-9f6e-ca3a8e2edba5
EEE

ERROR: test_login (accounts.tests.TestLogin)

Traceback (most recent call last):
File "最上位のプロジェクトディレクトリ\accounts\tests.py", line 18, in test_login
self.selenium.get('http://localhost:8000' + str(reverse_lazy('account_login')))
File "仮想環境のパス\lib\site-packages\django\utils\functional.py", line 140, in __text_cast
return func(*self.__args, **self._kw)
File "仮想環境のパス\lib\site-packages\django\urls\base.py", line 30, in reverse
resolver = get_resolver(urlconf)
File "仮想環境のパス\lib\site-packages\django\urls\resolvers.py", line 70, in get_resolver
urlconf = settings.ROOT_URLCONF
File "仮想環境のパス\lib\site-packages\django\conf_init
.py", line 83, in getattr
val = getattr(self.wrapped, name)
File "仮想環境のパス\lib\site-packages\django\conf_init
.py", line 239, in getattr
return getattr(self.default_settings, name)
AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF'

======================================================================
ERROR: test_login (accounts.tests.TestLogin)

Traceback (most recent call last):
File "仮想環境のパス\lib\site-packages\django\test\testcases.py", line 284, in _setup_and_call
self._post_teardown()
File "仮想環境のパス\lib\site-packages\django\test\testcases.py", line 1006, in _post_teardown
self._fixture_teardown()
File "仮想環境のパス\lib\site-packages\django\test\testcases.py", line 1038, in fixture_teardown
call_command('flush', verbosity=0, interactive=False,
File "仮想環境のパス\lib\site-packages\django\core\management_init
.py", line 181, in call_command
return command.execute(*args, **defaults)
File "仮想環境のパス\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "仮想環境のパス\lib\site-packages\django\core\management\commands\flush.py", line 47, in handle
sql_list = sql_flush(self.style, connection,
File "仮想環境のパス\lib\site-packages\django\core\management\sql.py", line 9, in sql_flush
tables = connection.introspection.django_table_names(only_existing=True, include_views=False)
File "仮想環境のパス\lib\site-packages\django\db\backends\base\introspection.py", line 99, in django_tab
le_names
existing_tables = set(self.table_names(include_views=include_views))
File "仮想環境のパス\lib\site-packages\django\db\backends\base\introspection.py", line 50, in table_name
s
with self.connection.cursor() as cursor:
File "仮想環境のパス\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "仮想環境のパス\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor
return self._cursor()
File "仮想環境のパス\lib\site-packages\django\db\backends\dummy\base.py", line 20, in complain
raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE va
lue. Check settings documentation for more details.

======================================================================
ERROR: diary.tests.test_views (unittest.loader._FailedTest)

ImportError: Failed to import test module: diary.tests.test_views
Traceback (most recent call last):
File "C:\Users\mamam\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 436, in _find_test_path
module = self._get_module_from_name(name)
File "C:\Users\mamam\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 377, in get_module_from
name
import(name)
File "最上位のプロジェクトディレクトリ\diary\tests\test_views.py", line 5, in <module>
from ..models import Diary
File "最上位のプロジェクトディレクトリ\diary\models.py", line 1, in <module>
from accounts.models import CustomUser
File "最上位のプロジェクトディレクトリ\accounts\models.py", line 1, in <module>
from django.contrib.auth.models import AbstractUser
File "仮想環境のパス\lib\site-packages\django\contrib\auth\models.py", line 5, in <module>
from django.contrib.contenttypes.models import ContentType
File "仮想環境のパス\lib\site-packages\django\contrib\contenttypes\models.py", line 133, in <module>
class ContentType(models.Model):
File "仮想環境のパス\lib\site-packages\django\db\models\base.py", line 113, in new
raise RuntimeError(
RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and is
n't in an application in INSTALLED_APPS.


Ran 2 tests in 6.600s

FAILED (errors=3)

試したこと

エラーコードに書かれている、編集した箇所を見返してみたのですが、記述ミスはなさそうでした、、

ツール

Python 3.9.1
PostgreSQL 10
PyCharm Community Edition 2021.1.2

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

holy_

2021/09/10 15:55

settings.pyに関してのエラーが多いためsettings.pyをコードを記載して頂きたいです
退会済みユーザー

退会済みユーザー

2021/09/11 00:15 編集

追記のご依頼いただいたプロジェクトの設定ファイルですが、以下のように分割しています。 ※本文は文字数制限で入らなかったのでこちらに記載します。 ①settings.py(本番運用環境用) 空です ②settings_common.py (本番と開発共通の設定ファイル) import os from pathlib import Path from django.contrib.messages import constants as messages # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-l+@hvl$k=ap!jx7@%-290yg69pobtd%2&n9yiu9egpoa!1hqba' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'diary.apps.DiaryConfig', 'accounts.apps.AccountsConfig', 'django.contrib.sites', 'allauth', 'allauth.account', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'combu.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'combu.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'combu', 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': '', 'PORT': '', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'ja' TIME_ZONE = 'Asia/Tokyo' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MESSAGE_TAGS = { messages.ERROR: 'alert alert-danger', messages.WARNING: 'alert alert-warning', messages.SUCCESS: 'alert alert-success', messages.INFO: 'alert alert-info', } AUTH_USER_MODEL = 'accounts.CustomUser' #django-allauthで利用するdjango.contrib.sitesを使うためにサイト識別用IDを設定 SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'allauth.account.auth_backends.AuthenticationBackend', #一般ユーザ―用(メールアドレス認証) 'django.contrib.auth.backends.ModelBackend', #管理用サイト用(ユーザー名認証) ) #メールアドレス認証に変更する設定 ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USERNAME_REQUIRED = False #サインアップにメールアドレス確認を挟むよう設定 ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_EMAIL_REQUIRED = True #ログイン/ログアウト後の遷移先を設定 LOGIN_REDIRECT_URL = 'diary:diary_list' ACCOUNT_LOGOUT_REDIRECT_URL = 'account_login' #ログアウトリンクのクリック一発でログアウトする設定 ACCOUNT_LOGOUT_ON_GET = True MEDIA_URL = '/media/' ③settings_dev.py(開発環境固有のファイル) from .settings_common import * # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] #ロギング設定 LOGGING = { 'version': 1, #1固定 'disable_existing_loggers': False, #ロガーの設定 'loggers': { #Djangoが利用するロガー 'django': { 'handlers': ['console'], 'level': 'INFO', }, #diaryアプリケーションが利用するロガー 'diary': { 'handlers': ['console'], 'level': 'DEBUG', }, }, #ハンドラの設定 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'dev' }, }, #フォーマッタの設定 'formatters': { 'dev': { 'format': '\t'.join([ '%(asctime)s', '[%(levelname)s]', '%(pathname)s(Line:%(lineno)d)', '%(message)s' ]) } } } EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') お手数ですが、ご確認お願い致します。
holy_

2021/09/11 00:57

2つ目ののエラーに関してはDBのHOSTとPORTが指定されていないので確認願いします。 テストでのsettingsを読み込みがうまくいっていないような気がします。 pytest.iniとconftest.pyなどの設定も気になります。 テストではなくpython mange.py runserverでは動くのでしょうか?
退会済みユーザー

退会済みユーザー

2021/09/11 02:49

ご回答ありがとうございます。 DBのHOSTとPORTについては、書籍ではテスト段階も空欄のままで良いようです。 Python manage.py runserverでは以下のエラーでました。 CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. ※PyCharmでrunserver起動した際は一見問題なさそうだったので見逃しておりました。 settingsの読み込みと上記のエラーについて調べてみます。 情報ありがとうございます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問