-1

在另一个文件中导入模型时出错。基本上我想用

>>> from mysite.blog.models import Blog
>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
>>> b.save()

但在 python 文件 [scrap.py] 中向模型添加值,但在此文件中导入模型时出错。有什么帮助吗??

from models import QuestionBox  // Error in this line

错误回溯:

Traceback (most recent call last):
  File "scrap.py", line 1, in <module>
    from models import QuestionBox
  File "/home/sourabh/Django/QASite/QAsite/QAapp/models.py", line 1, in <module>
    from django.db import models
  File "/home/sourabh/Django/QASite/local/lib/python2.7/site-packages/django/db/__init__.py", line 11, in <module>
    if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
  File "/home/sourabh/Django/QASite/local/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__
    self._setup(name)
  File "/home/sourabh/Django/QASite/local/lib/python2.7/site-packages/django/conf/__init__.py", line 46, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

目录树

    .
    |-- manage.py
    |-- QAapp
    |   |-- __init__.py
    |   |-- __init__.pyc
    |   |-- migrations
    |   |   |-- 0001_initial.py
    |   |   |-- 0001_initial.pyc
    |   |   |-- 0002_initial.py
    |   |   |-- 0002_initial.pyc
    |   |   |-- 0003_initial.py
    |   |   |-- 0003_initial.pyc
    |   |   |-- __init__.py
    |   |   `-- __init__.pyc
    |   |-- models.py
    |   |-- models.pyc
    |   |-- scrap.py
    |   |-- tests.py
    |   `-- views.py
    |-- QAappdb
    `-- QAsite
        |-- __init__.py
        |-- __init__.pyc
        |-- settings.py
        |-- settings.pyc
        |-- urls.py
        `-- wsgi.py

模型文件:

class QuestionBox :

    topic = models.CharField(max_length=50)
    sub_topic = models.CharField(max_length=50)

    question = models.TextField()
    options = models.TextField()
    correct_option = models.TextField()

    total_attempt = models.IntegerField()
    correct_attempt = models.IntegerField()
4

2 回答 2

1

问题 :

1) Python manage.py 包含用于数据库的路径设置文件。
2) 我正在导入一个模型 [QuestionBox ],它试图导入导致错误的 DATABASE 设置。

修补:

1) 在您想直接运行的文件 [scrap.py] 上明确包含这些行。

import os
   os.environ.setdefault("DJANGO_SETTINGS_MODULE", "QAsite.settings")
于 2013-09-18T05:20:53.163 回答
0

有几件事要检查:

  1. 根据您的文件路径,您需要在要导入的模块之前使用应用程序名称。所以:

    从 QAapp.models 导入 QuestionBox

  2. 检查文件的文件路径/目录路径settings.py

  3. 您的模型类应为:

    类问题框(models.Model):...

希望这有助于解决问题。

于 2013-09-18T00:03:31.353 回答