Unable to load a Django model from a separate directory in a database script

2024/11/17 19:29:58

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?

Answer

I just figured it out, of course right after finally posting the question! I was setting my django root directory to the wrong directory. I needed to set it to this

current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
root_dir = os.path.join(parent_dir, 'api')
sys.path.append(root_dir)

Now it works!

https://en.xdnf.cn/q/118769.html

Related Q&A

Leetcode problem 14. Longest Common Prefix (Python)

I tried to solve the problem (you can read description here: https://leetcode.com/problems/longest-common-prefix/) And the following is code I came up with. It gives prefix value of the first string in…

Python BS: Fetching rows with and without color attribute

I have some html that looks like this (this represents rows of data in a table, i.e the data between tr and /tr is one row in a table)<tr bgcolor="#f4f4f4"> <td height="25"…

Python multiple number guessing game

I am trying to create a number guessing game with multiple numbers. The computer generates 4 random numbers between 1 and 9 and then the user has 10 chances to guess the correct numbers. I need the fee…

How to produce a graph of connected data in Python?

Lets say I have a table of words, and each word has a "related words" column. In practice, this would probably be two tables with a one-to-many relationship, as each word can have more than o…

Syntax for reusable iterable?

When you use a generator comprehension, you can only use the iterable once. For example.>>> g = (i for i in xrange(10)) >>> min(g) 0 >>> max(g) Traceback (most recent call la…

Buildozer Problem. I try to make apk file for android, but i cant

artur@DESKTOP-SMKQONQ:~/Suka$ lsbuildozer.spec main.pyartur@DESKTOP-SMKQONQ:~/Suka$ buildozer android debugTraceback (most recent call last):File "/usr/local/bin/buildozer", line 10, in <…

how to run python script with ansible-playbook?

I want to print result in ansible-playbook but not working. python script: #!/usr/bin/python3import timewhile True:print("Im alive")time.sleep(5)deploy_python_script.yml:connection: localbeco…

How to concatenate pairs of row elements into a new column in a pandas dataframe?

I have this DataFrame where the columns are coordinates (e.g. x1,y1,x2,y2...). The coordinate columns start from the 8th column (the previous ones are irrelevant for the question) I have a larger exam…

Python: using threads to call subprocess.Popen multiple times

I have a service that is running (Twisted jsonrpc server). When I make a call to "run_procs" the service will look at a bunch of objects and inspect their timestamp property to see if they s…

Find a substring [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 5…