Why my django code cannot be a "standalone Django script",

before you look at my code, see http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/

I want to be a standalone Django script

this is my code:

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'

and this is the trace:

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.
+3
source share
1 answer

The code you use to install the django settings module must be in front of any code related to django, including importing django db at the top of the script.

+3
source

Source: https://habr.com/ru/post/1731636/


All Articles