Django 1.7 python standalone scripts


Here is a guide to set standalone python scripts in Django 1.7. Fyi, here is my project structures :

1
2
3
4
5
6
project_name
   |__ app
        |__ __init__.py
        |__ standalone.py
        |__ models.py
        |__ views.py

Then my standalone script be like:

1
2
3
4
5
6
7
8
9
10
import sys
import os

# Setup environ
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), ‘..’))

import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")
django.setup()

Some example :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import sys
import os

# Setup environ
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), ‘..’))

import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")
django.setup()

CURRENT = os.path.dirname(__file__)

from myapp.models import SomeModel

def importing(folderpath):
    folders = os.listdir(folderpath)

    for name in folders:
        try:
            SomeModel.objects.get(name=name)
        except SomeModel.DoesNotExist:
            print(name)

if __name__ == "__main__":
    folderpath = os.path.abspath(os.path.join(CURRENT, "..", "bulk_data"))
    importing(folderpath)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.