为什么Django不能正常运行?



我最近正在按照《Python Crash Course》一书中的描述学习Django。我按照每一步操作,试着从头重新启动几次,仍然无法解决问题(甚至重新安装MacOS以获得更干净的桌面)。下面是我的代码:


class Topic(models.Model):
'''A topic the user is learning about'''
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
'''Return a string represent model'''
return self.text

如下所示:

Traceback (most recent call last):
File "/Users/bryan/Desktop/python/learning_log/learning_logs/models.py", line 3, in <module>
class Topic(models.Model):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/base.py", line 108, in __new__
app_config = apps.get_containing_app_config(module)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 253, in get_containing_app_config
self.check_apps_ready()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 135, in check_apps_ready
settings.INSTALLED_APPS
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/conf/__init__.py", line 82, in __getattr__
self._setup(name)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/conf/__init__.py", line 63, in _setup
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
[Finished in 304ms with exit code 1]
[cmd: ['python3', '-u', '/Users/bryan/Desktop/python/learning_log/learning_logs/models.py']]
[dir: /Users/bryan/Desktop/python/learning_log/learning_logs]
[path: /Library/Frameworks/Python.framework/Versions/3.10/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin]

编辑:代码在models.py

文件中

似乎错误正在发生,因为您直接运行models.py文件。在使用Django时,很少直接运行.py文件。通常你在终端上运行一些命令,然后在浏览器中与你的项目交互。

  • 您是否在活跃的虚拟环境中工作?
  • 您是否为您的应用程序运行了makemigrations命令?
  • 运行python manage.py migrate了吗?
  • 当你运行python manage.py runserver时会发生什么?

有一个小错误,你试图访问__str__方法中的text,由于它未能访问text,你需要更改代码,如self.text

def __str__(self):
'''Return a string represent model'''
return self.text

相关内容

  • 没有找到相关文章

最新更新