Forums

Unable to import Django modules in PythonAnywhere Tasks

Hello everybody,

I'm having a hard time setting up my tasks on Python Anywhere.

I use Django and the task I want to perform requires that I import a model from /home/username/myproject/app/models.py.

I first started by trying to call the task as follow:

python3.8 /home/username/myproject/myapp/tasks.py

Which of course yielded the import error telling me it was impossible to import my module myapp/models.py.

Following the instructions on this page: https://help.pythonanywhere.com/pages/VirtualEnvInScheduledTasks I understood that I needed to call the tasks through my virtual environment. I then tried the suggested method with:

/home/username/.virtualenvs/myproject/bin/python3.8 /home/username/myproject/myapp/tasks.py

This time I received a configuration error:

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

I'm not sure what this means or how to fix that. Since I saw another alternative I then tried to follow the instructions for environment variables. My task looks like this:

source virtualenvwrapper.sh && workon /home/username/.virtualenvs/myproject && python3.8 /home/username/myproject/myapp/tasks.py

This tells me it doesn't recognize the environment ("Environment '/home/username/.virtualenvs/myproject' does not exist ").

EDIT: I realized the name of my virtual environment was required instead of its path. My command should have been:

source virtualenvwrapper.sh && workon virtual_env_name && python3.8 /home/username/myproject/myapp/tasks.py

Which yields another error:

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

Would anybody know how I could get my task to work?

Thank you very much for your help.

you should write a django management command, and call it using manage.py command_name

Hello Conrad,

You are correct, approaching this problem with a Django Management command was the right way to solve it.

For anybody in the same situation as me you should read about Management Command in the Django documentation right here: https://docs.djangoproject.com/en/3.0/howto/custom-management-commands/

My task now looks like this:

source virtualenvwrapper.sh && workon virtual_env_name && python3.8 /home/username/my_project/manage.py management_command_name

and it works fine.

Thank you very much for the help.

Excellent -- glad to hear you got it working!