[Django]-Django 1.6 run stand alone script in Django Environment- No Success

3👍

To run standalone script you just need to write this code before you start your script. The problem in executing standalone script is it can not find django environment so to provide this we need to append setting file.

//Start your code here

import os, sys
from os import path

proj_path = "project_path\project_name"

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")
sys.path.append(proj_path)
os.chdir(proj_path)

from django.core.wsgi import get_wsgi_application

from app1.models import *
from app2.models import model_name
from app3.models import model_name1, model_name2

application = get_wsgi_application()

//Start your script from here 
👤sujit

2👍

The answer is really simple…just paste what is in manage.py:

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bot_server.settings.local")

    from django.core.management import execute_from_command_line

With all the posts I have read, I can not believe that this was not mentioned before.

👤dman

1👍

Yes this answer is making simple

manage.py file as belows

#!/usr/bin/env python

from settings.common import PROJECT_ROOT
import os
import sys


os.chdir(PROJECT_ROOT)
sys.path.insert(0, os.path.abspath(os.path.join(PROJECT_ROOT, "..")))

for i, arg in enumerate(sys.argv):
   if arg.startswith("--site"):
      os.environ["MEZZANINE_SITE_ID"] = arg.split("=")[1]
      sys.argv.pop(i)

if __name__ == "__main__":
    settings_module = "settings.common"
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

Leave a comment