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/

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

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

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

Following the instructions on this page: 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/

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 && workon /home/username/.virtualenvs/myproject && python3.8 /home/username/myproject/myapp/

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 && workon virtual_env_name && python3.8 /home/username/myproject/myapp/

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 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:

My task now looks like this:

source && workon virtual_env_name && python3.8 /home/username/my_project/ management_command_name

and it works fine.

Thank you very much for the help.

Excellent -- glad to hear you got it working!