I am having difficulty writing a python script that takes a directory of .txt files and loads them into my database that is utilized in a Django project. Based on requirements the python script needs to be located in a separate directory than the api (my django directory).
Here is my project structure currently:
Main-Project/database/text-script.pytext-files/example-file.txtdjango/django/settings.pysnippets/models.py
My text-script.py file looks like this:
import os
import sys
import djangocurrent_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django.django.settings')
django.setup()from django.snippets.models import Snippetdef import_articles(directory):for filename in os.listdir(directory):if filename.endwith('.txt'):with open(os.path.join(directory, filename), 'r') as file:content = file.read()Snippet.objects.create(filename=filename, content=content)if __name__ == '__main__':text_dir = os.path.join(current_dir, 'text-files')import_articles(text_dir)
My installed apps looks like this:
INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','snippets.apps.SnippetsConfig',
]
I get this error when I try to run the script:
ModuleNotFoundError: No module named 'snippets'
How do I correctly load the Snippet model from my Django project to utilize the same database used in my Django project?