gpt4 book ai didi

python - 为什么我的 Django 代码不能是 'Standalone Django scripts'

转载 作者:行者123 更新时间:2023-11-28 16:54:31 26 4
gpt4 key购买 nike

在查看我的代码之前,请参阅 http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/

我想成为独立的 Django 脚本

这是我的代码:

from django.db import models
from djangosphinx.models import SphinxSearch,SphinxQuerySet


import os
os.environ["DJANGO_SETTINGS_MODULE"] = "sphinx_test.settings"

from django.core.management import setup_environ
from sphinx_test import settings

setup_environ(settings)

DJANGO_SETTINGS_MODULE=sphinx_test.settings

class File(models.Model):
name = models.CharField(max_length=200)
tags = models.CharField(max_length=200)

objects = models.Manager()
search = SphinxQuerySet(index="test1")


import datetime


class Group(models.Model):
name = models.CharField(max_length=32)

class Document(models.Model):
group = models.ForeignKey(Group)
date_added = models.DateTimeField(default=datetime.datetime.now)
title = models.CharField(max_length=32)
content = models.TextField()

search = SphinxQuerySet(File,index="test1")

class Meta:
db_table = 'documents'

这是回溯:

Traceback (most recent call last):
File "D:\zjm_code\sphinx_test\models.py", line 1, in <module>
from django.db import models
File "D:\Python25\Lib\site-packages\django\db\__init__.py", line 10, in <module>
if not settings.DATABASE_ENGINE:
File "D:\Python25\Lib\site-packages\django\utils\functional.py", line 269, in __getattr__
self._setup()
File "D:\Python25\Lib\site-packages\django\conf\__init__.py", line 38, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

最佳答案

用于设置 django 设置模块的代码必须位于任何与 django 相关的代码之前,包括脚本顶部的 django 数据库导入。

关于python - 为什么我的 Django 代码不能是 'Standalone Django scripts',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2211624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com