1

I am developing an app in Django.

I want to load data inside my model, that is glossary_entry, but the data is stored inside an xlsx file, that is dati_prova.xlsx.

In order to achieve this, I have developed the following script:

import pandas as pd
from django.conf import settings

settings.configure()

from myapp.models import glossary_entry #this is line 7
 
path=r"mypath\dati_prova.xlsx"
 
with open(path) as f:
        reader = pd.read_excel(f)
        next(reader, None)  # skip the headers

        for row in reader:
                _, created = glossary_entry.objects.get_or_create(
                Lemma = row[0],
                Acronym = row[1],
                Definizione = row[2],
                )
            # creates a tuple of the new object or
            # current object and a boolean of if it was created

But when I run it from Anaconda prompt, I get

File "load_glossary.py", line 7, in module ...

raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

What's the problem?

Please note:

My app runs fine, just the uploading-data script fails.

Please note:

I copy pasted

from django.conf import settings

settings.configure()

from stack overflow answers because I was getting the error:

django.core.exceptions.ImproperlyConfigured: Requested setting USE_TZ, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

but I don't have experience and I don't understand what was the error.

Update

I have read on https://groups.google.com/forum/#!topic/django-users/bF_lRbzzguA that it could be that

The problem is that one of your applications imports models in its top-level init.py. This is not supported; for an explanation, you can read https://docs.djangoproject.com/en/1.9/ref/applications/#how-applications-are-loaded

Update

I changed the file as following:

import pandas as pd

from django.conf import settings
settings.configure()

import django
django.setup() 


from myapp.models import mymodel
 
path=r"mypath\dati_prova.xlsx"
 
with open(path) as f:
        reader = pd.read_excel(f)
        next(reader, None)  # skip the headers

And now I get:

RuntimeError: Model class myapp.models.mymodel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

But it is not true, since in settings.py I wrote my app name, and the project runs fine. Just the script does not work... It is like python cannot read my settings.py . What's the problem? Maybe is it reading another set

Update

As suggested here https://stackoverflow.com/a/38821174/7658051
I have moved my script load_glossary.py into

myapp>management>commands


made a copy of my xlsx file into a csv one
and updated the code as follows:
# myapp/management/commands/load_glossary.py

from django.core.management.base import BaseCommand, CommandError
import csv

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('csv_file', nargs='+', type=str)

    def handle(self, *args, **options):
        for csv_file in options['csv_file']:
            dataReader = csv.reader(open(csv_file), delimiter=',', quotechar='"')
            for row in dataReader:
                
                Lemma=row[0],
                Acronym=row[1],
                Definition=row[2],
                
                
                # etc...
                self.stdout.write(
                    'Created glossary entry'
                
                )

And I am lunching it by typing into anaconda prompt

python ./manage.py load_glossary csv_file "mypath\dati_prova.csv"

But then I get

line 20, in handle dataReader = csv.reader(open(csv_file), delimiter=',', quotechar='"') FileNotFoundError: [Errno 2] No such file or directory: 'csv_file'

What's wrong this time?

Tms91
  • 3,456
  • 6
  • 40
  • 74
  • 1
    I hope it helps https://stackoverflow.com/a/28297987/1734707 – planet260 Oct 09 '19 at 13:42
  • thanks, it brought me to update the code as shown here https://stackoverflow.com/a/58322333/7658051 but still it's like python it's not reading my settings – Tms91 Oct 10 '19 at 11:57
  • what you show as the latest version of your code no longer has the `from django.conf import settings` -- that would indeed prevent it from reading the settings. – Rayanth Dec 29 '19 at 03:26

1 Answers1

1

I solved the problem by substituting this:

import pandas as pd
from django.conf import settings

settings.configure()

from myapp.models import glossary_entry #this is line 7

path=r"mypath\dati_prova.xlsx"

with open(path) as f:
        reader = pd.read_excel(f)
        next(reader, None)  # skip the headers

        for row in reader:
                _, created = glossary_entry.objects.get_or_create(
                Lemma = row[0],
                Acronym = row[1],
                Definizione = row[2],
                )
            # creates a tuple of the new object or
            # current object and a boolean of if it was created

with this:

import pandas as pd
from myapp.models import glossary_entry

def pour_entire_entry_model():

    elements = glossary_entry.objects.all() 

    for element in elements:

        entry = acquired_terminology.objects.create()

        entry.Lemma = element.Lemma
        entry.Acronym = element.Acronym
        entry.Definizione = element.Definizione 

            # creates a tuple of the new object or
            # current object and a boolean of if it was created
Tms91
  • 3,456
  • 6
  • 40
  • 74
  • I followed your steps because I had the same root problem and recreated your errors along the way up until the last step. When i run "python3 manage.py myscript" it just tells me "Unknown command: 'query_and_save_temperatures'". Any tips? Did your solutions still use the management/commands folder? – Casey Schneider Jan 27 '22 at 19:53
  • 1
    In django you should always run your app by running `python manage.py runserver`. Still, it sounds like some path or directory name is mismatching. However, that is too little information to find out what is wrong. You'd better open a question providing all the context to reproduce the error. – Tms91 Jan 27 '22 at 20:34
  • Okay. Thank you by the way for updating your question and providing your solution. Helps a lot. – Casey Schneider Jan 27 '22 at 20:38