Forums

Calling User and Django Model in Task

Having some troubling utilizing the app's User and other model's. I'm given the error --

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

I've tried activating the env path with this :

source /home/name/app_name/bin/activate &&
/home/name/app_name/bin/python
/home/name/scripts/update_tracking.py

And also putting the task folder within my app directory.

Who has done this before and how can I get it done myself?

[edit by admin: formatting]

I switched to using a management command. The command is executed successfully but the actual logic isn't carried out. Is there something wrong with this set-up?

from django.core.management.base import BaseCommand, CommandError from
emails.models import Tracking import datetime

class Command(BaseCommand):
    help = 'Command to delete tracking'

    def add_argument(self, parser):
        pass

    def handle(self, *args, **options):
        try:
            Tracking.objects.filter(timestamp__lte=datetime.now()-datetime.timedelta(days=90)).delete()

        except Exception as e:
            CommandError(repr(e))

[edit by admin: formatting]

A management command is certainly the "official" Django way to do this kind of thing, so I'd certainly expect it to work. Perhaps you could get more information by adding some print statements to work out what it's doing? I'm imagining something like this:

def handle(self, *args, **options):
    try:
        print("Getting objects to delete")
        objects_to_delete = Tracking.objects.filter(timestamp__lte=datetime.now()-datetime.timedelta(days=90))
        print("About to delete {} objects".format(objects_to_delete.count()))
        objects_to_delete.delete()
        print("Objects deleted")

    except Exception as e:
        print("Something went wrong: {}".format(e))
        CommandError(repr(e))

Also, one thing I should check: are you running the management command using manage.py? You need to run it like this:

./manage.py mycommand

...where mycommand.py is the name of the Python script file. If you just run

python3.6 mycommand.py

...then it will do nothing.