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

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

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

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

Python

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

Q&A

1回答

7910閲覧

【ハマってます】django RuntimeErrorを解決したい

tonytony

総合スコア11

Django

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

Python

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

0グッド

0クリップ

投稿2020/06/16 03:14

概要

runserverしようとしたところ、
RuntimeError: Model class pairnite.users.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
というエラーが出てしまい、色々調べて試してみてを繰り返したのですが、どうにも解決できず、この場で質問させていただきます。
不明な点や足りない部分があれば、お気軽にご質問ください。

環境

Python3.7.3
Django3.0.6

わかる範囲での原因の予想

リアルタイムチャット昨日のため、websocketのchannelsの導入によるエラー

ディレクトリ構造

一番下に記載

コード(足りない部分あれば教えてください)

settings.py

1""" 2Django settings for config project. 3 4Generated by 'django-admin startproject' using Django 3.0.6. 5 6For more information on this file, see 7https://docs.djangoproject.com/en/3.0/topics/settings/ 8 9For the full list of settings and their values, see 10https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/ 21 22# SECURITY WARNING: keep the secret key used in production secret! 23SECRET_KEY = '&q9t+ez0k4r_ow$vm!y=mlgxtl4qk12ph58jyvg&#05j+tshe1' 24 25# SECURITY WARNING: don't run with debug turned on in production! 26DEBUG = True 27 28ALLOWED_HOSTS = [] 29 30AUTH_USER_MODEL = 'users.User' 31 32 33# Application definition 34INSTALLED_APPS = [ 35 'django.contrib.admin', 36 'django.contrib.auth', 37 'django.contrib.contenttypes', 38 'django.contrib.sessions', 39 'django.contrib.messages', 40 'django.contrib.staticfiles', 41 'users.apps.UsersConfig', 42 'relations.apps.RelationsConfig', 43 # フォーム処理用 44 "widget_tweaks", 45 'chat.apps.ChatConfig', 46 # # リアルタイムチャット実現用 47 'channels', 48] 49 50 51MIDDLEWARE = [ 52 'django.middleware.security.SecurityMiddleware', 53 'django.contrib.sessions.middleware.SessionMiddleware', 54 'django.middleware.common.CommonMiddleware', 55 'django.middleware.csrf.CsrfViewMiddleware', 56 'django.contrib.auth.middleware.AuthenticationMiddleware', 57 'django.contrib.messages.middleware.MessageMiddleware', 58 'django.middleware.clickjacking.XFrameOptionsMiddleware', 59] 60 61ROOT_URLCONF = 'config.urls' 62 63TEMPLATES = [ 64 { 65 'BACKEND': 'django.template.backends.django.DjangoTemplates', 66 'DIRS': [os.path.join(BASE_DIR, 'templates')], 67 'APP_DIRS': True, 68 'OPTIONS': { 69 'context_processors': [ 70 'django.template.context_processors.debug', 71 'django.template.context_processors.request', 72 'django.contrib.auth.context_processors.auth', 73 'django.contrib.messages.context_processors.messages', 74 ], 75 }, 76 }, 77] 78 79WSGI_APPLICATION = 'config.wsgi.application' 80 81 82# Database 83# https://docs.djangoproject.com/en/3.0/ref/settings/#databases 84 85DATABASES = { 86 'default': { 87 'ENGINE': 'django.db.backends.sqlite3', 88 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 89 } 90} 91 92 93# Password validation 94# https://docs.djangoproject.com/en/3.0/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/3.0/topics/i18n/ 114 115LANGUAGE_CODE = 'ja' 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/3.0/howto/static-files/ 128 129STATIC_URL = '/static/' 130 131# アイコン画像の保存先設定 132MEDIA_ROOT = os.path.join(BASE_DIR, 'media') 133MEDIA_URL = '/media/' 134 135# ログイン後のリダイレクト先 136LOGIN_REDIRECT_URL = "users:home" 137# ログアウト後のリダイレクト先 138LOGOUT_REDIRECT_URL = "users:index" 139# Channelsを有効化。channelsは非同期処理をサポートする。 140# https://qiita.com/massa142/items/cbd508efe0c45b618b34#:~:text=Django%20Channels%E3%81%A8%E3%81%AF&text=Channels%E3%81%AF%E3%80%81Django%E3%81%8CWebSocket,%E3%81%AB%E3%81%99%E3%82%8B%E3%83%97%E3%83%AD%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E3%81%A7%E3%81%82%E3%82%8B%E3%80%82 141ASGI_APPLICATION = 'config.routing.application' 142# channel layerの有効化。channel layerは複数ユーザーの間でメッセージを共有できる仕組み。docker環境に写したとき、hostsの第一引数をredisに変えた方がいいかも。 143# http://www.denzow.me/entry/2018/04/03/002351 144CHANNEL_LAYERS = { 145 'default': { 146 'BACKEND': 'channels_redis.core.RedisChannelLayer', 147 'CONFIG': { 148 "hosts": [("127.0.0.1", 6379)], 149 }, 150 }, 151} 152

chat/routings.py

1from django.urls import path 2 3from . import consumers 4 5websocket_urlpatterns = [ 6 path('ws/chat/<str:room_name>/', consumers.WSBackend), 7]

chat/urls.py

1from django.urls import path 2# from .views import index, user, reaction, chat 3from django.conf import settings 4from django.conf.urls.static import static 5# from .controller import chat_controller 6from . import views 7 8app_name = 'chat' 9 10urlpatterns = [ 11 path('create/<int:user_id>', views.create, name='chat_create'), 12 path('show/<int:room_id>', views.show, name='chat_show'), 13 path('create/<int:room_id>/messages/', views.messages, name='chat_messages'), 14]

config/urls.py

1from django.contrib import admin 2from django.urls import include, path 3from django.conf import settings 4from django.conf.urls.static import static 5 6urlpatterns = [ 7 path('admin/', admin.site.urls), 8 path('users/', include('users.urls')), 9 10 # ログイン用 11 path('users/', include('django.contrib.auth.urls')), 12 # チャット用 13 path('chat/', include('chat.urls')), 14 # リレーション用 15 path('relations/', include('relations.urls')), 16] 17 18# 画像をアドミン以外の人でも見れるようにする 19urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 20

ディレクトリ構造

量が多いです。
chatディレクトリとconfigディレクトリ以外見る必要ないと思います。

. ├── Pipfile ├── Pipfile.lock ├── chat │   ├── __init__.py │   ├── __pycache__ │   │   ├── __init__.cpython-37.pyc │   │   ├── admin.cpython-37.pyc │   │   ├── apps.cpython-37.pyc │   │   ├── chat_controller.cpython-37.pyc │   │   ├── models.cpython-37.pyc │   │   ├── urls.cpython-37.pyc │   │   └── views.cpython-37.pyc │   ├── admin.py │   ├── apps.py │   ├── chat_controller.py │   ├── consumers.py │   ├── forms.py │   ├── migrations │   │   ├── __init__.py │   │   └── __pycache__ │   │   └── __init__.cpython-37.pyc │   ├── models.py │   ├── routing.py │   ├── tests.py │   ├── urls.py │   └── views.py ├── config │   ├── __init__.py │   ├── __pycache__ │   │   ├── __init__.cpython-37.pyc │   │   ├── routing.cpython-37.pyc │   │   ├── settings.cpython-37.pyc │   │   ├── urls.cpython-37.pyc │   │   └── wsgi.cpython-37.pyc │   ├── routing.py │   ├── settings.py │   ├── urls.py │   └── wsgi.py ├── db.sqlite3 ├── manage.py ├── media │   └── icon │   ├── 1487784.jpg │   ├── Hi_�\202��\203��\203\210�\203\233�\203��\203\210_1.png │   ├── default.jpg │   ├── �\202��\202��\203��\203��\203��\202��\203��\203\203�\203\210_2020-06-06_13.34.42.png │   ├── �\203��\202��\226\207�\227ZZOO_w.jpg │   └── �\214�\221�\226��\202��\202場�\217模.jpg ├── relations │   ├── __init__.py │   ├── __pycache__ │   │   ├── __init__.cpython-37.pyc │   │   ├── admin.cpython-37.pyc │   │   ├── apps.cpython-37.pyc │   │   ├── forms.cpython-37.pyc │   │   ├── models.cpython-37.pyc │   │   ├── urls.cpython-37.pyc │   │   └── views.cpython-37.pyc │   ├── admin.py │   ├── apps.py │   ├── forms.py │   ├── migrations │   │   ├── 0001_initial.py │   │   ├── __init__.py │   │   └── __pycache__ │   │   ├── 0001_initial.cpython-37.pyc │   │   └── __init__.cpython-37.pyc │   ├── models.py │   ├── tests.py │   ├── urls.py │   └── views.py ├── templates │   ├── base.html │   ├── chat │   │   └── chat.html │   ├── home.html │   ├── index.html │   ├── registration │   │   └── login.html │   ├── relations │   │   ├── dislike.html │   │   └── like.html │   └── users │   ├── delete.html │   ├── detail.html │   ├── mail_change.html │   ├── password_change.html │   ├── password_change_done.html │   ├── signup.html │   └── update.html └── users ├── __init__.py ├── __pycache__ │   ├── __init__.cpython-37.pyc │   ├── admin.cpython-37.pyc │   ├── apps.cpython-37.pyc │   ├── forms.cpython-37.pyc │   ├── mixins.cpython-37.pyc │   ├── models.cpython-37.pyc │   ├── urls.cpython-37.pyc │   └── views.cpython-37.pyc ├── admin.py ├── apps.py ├── forms.py ├── migrations │   ├── 0001_initial.py │   ├── __init__.py │   └── __pycache__ │   ├── 0001_initial.cpython-37.pyc │   ├── 0002_auto_20200606_1415.cpython-37.pyc │   ├── 0003_auto_20200607_1537.cpython-37.pyc │   ├── 0004_auto_20200608_0835.cpython-37.pyc │   └── __init__.cpython-37.pyc ├── mixins.py ├── models.py ├── tests.py ├── urls.py └── views.py

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

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

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

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

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

guest

回答1

0

setting.pyのINSTALLED_APPSに
'chat.apps.UsersConfig'
もしくは
'users'
の追加が必要な気がします。

投稿2020/06/16 03:30

llr114

総合スコア203

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

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

tonytony

2020/06/16 21:52

ご回答いただきありがとうございます。 試してみましたが、解決には至りませんでした。 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', 'relations.apps.RelationsConfig', # フォーム処理用 "widget_tweaks", 'chat.apps.ChatConfig', # # リアルタイムチャット実現用 'channels', ] ChatConfig自体は問題なく設定できていると思うんですよね......。
llr114

2020/06/17 01:56

Runserverのコマンドを実行した後に、コンソールにエラー文が表示されるということですよね? RuntimeError: Model class pairnite.users.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. 以外にも、何か表示されていますでしょうか? もしあれば全文欲しいです。
tonytony

2020/06/17 10:36

ご返信いただきありがとうございます! なんとかエラーを解消したい一心です。 以下になります。 Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/Users/tonytony/PycharmProjects/pairnite/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/tonytony/PycharmProjects/pairnite/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/tonytony/PycharmProjects/pairnite/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/tonytony/PycharmProjects/pairnite/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/tonytony/PycharmProjects/pairnite/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/tonytony/PycharmProjects/pairnite/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/tonytony/PycharmProjects/pairnite/venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/tonytony/PycharmProjects/pairnite/venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/tonytony/PycharmProjects/pairnite/pairnite/chat/models.py", line 2, in <module> from pairnite.users.models import Profile File "/Users/tonytony/PycharmProjects/pairnite/pairnite/users/models.py", line 40, in <module> class User(AbstractBaseUser, PermissionsMixin): File "/Users/tonytony/PycharmProjects/pairnite/venv/lib/python3.7/site-packages/django/db/models/base.py", line 115, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class pairnite.users.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
llr114

2020/06/17 10:41

usersのmodels.pyも見せていただいてもいいですか? お手数おかけします。
tonytony

2020/06/17 21:48

なんどもありがとうございます!本当に助かります。 こちらになります! from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.core.mail import send_mail from django.contrib.auth.models import PermissionsMixin, UserManager from django.contrib.auth.base_user import AbstractBaseUser from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.translation import ugettext_lazy as _ from django.utils import timezone class CustomUserManager(UserManager): """ユーザーマネージャー""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): """カスタムユーザーモデル.""" email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) objects = CustomUserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_short_name(self): """Return the short name for the user.""" return self.email def email_user(self, subject, message, from_email=None, **kwargs): """Send an email to this user.""" send_mail(subject, message, from_email, [self.email], **kwargs) @property def username(self): """username属性のゲッター 他アプリケーションが、username属性にアクセスした場合に備えて定義 メールアドレスを返す """ return self.email # OneToOneで、ユーザーモデルに紐付ける class Profile(models.Model): # 性別,年齢,ゲームデバイス,通話可能か,通話デバイス,プレイスタイル,プレイ時間帯,建築レベル,一言メッセージ id = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(_('user name'), null=True, max_length=20, blank=True) icon = models.ImageField(blank=True, null=True, upload_to='icon') gender = models.CharField(max_length=20, null=True, blank=True) age = models.IntegerField(validators=[MinValueValidator(12), MaxValueValidator(120)], null=True, blank=True) game_device = models.CharField(max_length=30, null=True, blank=True) voice = models.CharField(max_length=30, null=True, blank=True) voice_device = models.CharField(max_length=30, null=True, blank=True) play_style = models.CharField(max_length=30, null=True, blank=True) play_time = models.CharField(max_length=30, null=True, blank=True) craft_level = models.CharField(max_length=30, null=True, blank=True) one_message = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save()
llr114

2020/06/18 01:54

models.pyの from django.contrib.auth.models import PermissionsMixin, UserManager from django.contrib.auth.base_user import AbstractBaseUser を from django.contrib.auth.models import PermissionsMixin, UserManager, AbstractBaseUser に変えたらどうでしょうか?
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

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

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

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問