【ハマってます】django RuntimeErrorを解決したい
受付中
回答 1
投稿
- 評価
- クリップ 0
- VIEW 669
概要
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の導入によるエラー
ディレクトリ構造
一番下に記載
コード(足りない部分あれば教えてください)
"""
Django settings for config project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&q9t+ez0k4r_ow$vm!y=mlgxtl4qk12ph58jyvgj+tshe1'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
AUTH_USER_MODEL = 'users.User'
# Application definition
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',
]
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 = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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 = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/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.0/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.0/howto/static-files/
STATIC_URL = '/static/'
# アイコン画像の保存先設定
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# ログイン後のリダイレクト先
LOGIN_REDIRECT_URL = "users:home"
# ログアウト後のリダイレクト先
LOGOUT_REDIRECT_URL = "users:index"
# Channelsを有効化。channelsは非同期処理をサポートする。
# 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
ASGI_APPLICATION = 'config.routing.application'
# channel layerの有効化。channel layerは複数ユーザーの間でメッセージを共有できる仕組み。docker環境に写したとき、hostsの第一引数をredisに変えた方がいいかも。
# http://www.denzow.me/entry/2018/04/03/002351
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [("127.0.0.1", 6379)],
},
},
}
from django.urls import path
from . import consumers
websocket_urlpatterns = [
path('ws/chat/<str:room_name>/', consumers.WSBackend),
]
from django.urls import path
# from .views import index, user, reaction, chat
from django.conf import settings
from django.conf.urls.static import static
# from .controller import chat_controller
from . import views
app_name = 'chat'
urlpatterns = [
path('create/<int:user_id>', views.create, name='chat_create'),
path('show/<int:room_id>', views.show, name='chat_show'),
path('create/<int:room_id>/messages/', views.messages, name='chat_messages'),
]
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('users.urls')),
# ログイン用
path('users/', include('django.contrib.auth.urls')),
# チャット用
path('chat/', include('chat.urls')),
# リレーション用
path('relations/', include('relations.urls')),
]
# 画像をアドミン以外の人でも見れるようにする
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
ディレクトリ構造
量が多いです。
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
-
気になる質問をクリップする
クリップした質問は、後からいつでもマイページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
クリップを取り消します
-
良い質問の評価を上げる
以下のような質問は評価を上げましょう
- 質問内容が明確
- 自分も答えを知りたい
- 質問者以外のユーザにも役立つ
評価が高い質問は、TOPページの「注目」タブのフィードに表示されやすくなります。
質問の評価を上げたことを取り消します
-
評価を下げられる数の上限に達しました
評価を下げることができません
- 1日5回まで評価を下げられます
- 1日に1ユーザに対して2回まで評価を下げられます
質問の評価を下げる
teratailでは下記のような質問を「具体的に困っていることがない質問」、「サイトポリシーに違反する質問」と定義し、推奨していません。
- プログラミングに関係のない質問
- やってほしいことだけを記載した丸投げの質問
- 問題・課題が含まれていない質問
- 意図的に内容が抹消された質問
- 過去に投稿した質問と同じ内容の質問
- 広告と受け取られるような投稿
評価が下がると、TOPページの「アクティブ」「注目」タブのフィードに表示されにくくなります。
質問の評価を下げたことを取り消します
この機能は開放されていません
評価を下げる条件を満たしてません
質問の評価を下げる機能の利用条件
この機能を利用するためには、以下の事項を行う必要があります。
- 質問回答など一定の行動
-
メールアドレスの認証
メールアドレスの認証
-
質問評価に関するヘルプページの閲覧
質問評価に関するヘルプページの閲覧
+1
setting.pyのINSTALLED_APPSに
'chat.apps.UsersConfig'
もしくは
'users'
の追加が必要な気がします。
投稿
-
回答の評価を上げる
以下のような回答は評価を上げましょう
- 正しい回答
- わかりやすい回答
- ためになる回答
評価が高い回答ほどページの上位に表示されます。
-
回答の評価を下げる
下記のような回答は推奨されていません。
- 間違っている回答
- 質問の回答になっていない投稿
- スパムや攻撃的な表現を用いた投稿
評価を下げる際はその理由を明確に伝え、適切な回答に修正してもらいましょう。
15分調べてもわからないことは、teratailで質問しよう!
- ただいまの回答率 88.33%
- 質問をまとめることで、思考を整理して素早く解決
- テンプレート機能で、簡単に質問をまとめられる
2020/06/17 06: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自体は問題なく設定できていると思うんですよね......。
2020/06/17 10:56
RuntimeError: Model class pairnite.users.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
以外にも、何か表示されていますでしょうか?
もしあれば全文欲しいです。
2020/06/17 19: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.
2020/06/17 19:41
お手数おかけします。
2020/06/18 06: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()
2020/06/18 10:54
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
に変えたらどうでしょうか?