将Django模型导入PyCharm的Python控制台

时间:2017-11-03 00:00:52

标签: django python-3.x pycharm

我正在关注Django教程并使用PyCharm。我正在尝试从models.py导入QuestionChoice到PyCharm“Python控制台”。我有__init__.py个文件位于顶级mysite,低级mysite和polls目录中。

我正在使用虚拟环境,它在PyCharm Python控制台中激活。

C:\Users\Jarad\PycharmProjects\OfficialDjangoTutorial\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm 2017.1.5\helpers\pydev\pydevconsole.py" 51164 51165
PyDev console: starting.

import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['C:\\Users\\Jarad\\PycharmProjects\\OfficialDjangoTutorial', 'C:/Users/Jarad/PycharmProjects/OfficialDjangoTutorial'])

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
>>> import sys
>>> import os
>>> import django
>>> os.getcwd()
'C:\\Users\\Jarad\\PycharmProjects\\OfficialDjangoTutorial'
sys.path.append('C:\\Users\\Jarad\\PycharmProjects\\OfficialDjangoTutorial\mysite')
>>> os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.mysite.settings'
>>> django.setup()
>>> from mysite.polls.models import Question, Choice
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm 2017.1.5\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "C:\Users\Jarad\PycharmProjects\OfficialDjangoTutorial\mysite\polls\models.py", line 8, in <module>
    class Question(models.Model):
  File "C:\Users\Jarad\PycharmProjects\OfficialDjangoTutorial\venv\lib\site-packages\django\db\models\base.py", line 118, in __new__
    "INSTALLED_APPS." % (module, name)
RuntimeError: Model class mysite.polls.models.Question doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

apps.py

from django.apps import AppConfig

class PollsConfig(AppConfig):
    name = 'polls'

重申我的目标:在PyCharm的“Python控制台”中导入QuestionChoice模型,因为对象的代码提示和检查将更好地帮助我学习方法和功能参数。

请告诉我我做错了什么。

PyCharm Python Console

1 个答案:

答案 0 :(得分:2)

打开你的&#39; settings.py&#39;在你的'mysite&#39;中存档目录并添加&#39;民意调查&#39;到安装的应用程序列表,如:

    # Application definition
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'polls',
    ]

由于你使用的是pycharm,你可以直接进入python控制台并使用

导入问题和选择
from polls.models import Question, Choice