Working with Django

Import existing Django models, etc. in an Airplane task
Airplane works with Django! You can write Python tasks like you normally would, plus a few additional lines of code to configure Django.

In brief

Add the following code to the beginning of your Airplane task:
python
Copied
1
import os
2
import sys
3
# Assumes this task is run from the parent directory
4
# Airplane will use the directory that requirements.txt is in
5
sys.path.insert(0, os.getcwd())
6
# Importing from myproject.wsgi configures Django
7
# Replace myproject with your Django project name
8
from myproject.wsgi import application
This configures your Python path to allow importing from the root directory, then initializes Django so you Django models, etc. are properly set up.
You'll need to configure the task Environment Variables the same way you'd configure Django in production. For example, you should set DATABASE_URL if you need to connect to a database.

Walkthrough

In this guide, we'll use the following example layout (replace myproject with the name of your Django project—myapp is an example Django application you might want to import from):
Copied
1
requirements.txt
2
airplane/
3
my_airplane_task.py
4
myapp/
5
__init__.py
6
models.py
7
myproject/
8
__init__.py
You might have something like the following if you ran airplane tasks init --from my_airplane_task:
python
Copied
1
# Linked to https://app.airplane.dev/t/my_airplane_task [do not edit this line]
2
3
def main(params):
4
print("parameters:", params)
To import from Django, add the following code to the top of your file:
python
Copied
1
# Linked to https://app.airplane.dev/t/my_airplane_task [do not edit this line]
2
3
# DJANGO SETUP
4
import os
5
import sys
6
# Assumes this task is run from the parent directory
7
# Airplane will use the directory that requirements.txt is in
8
sys.path.insert(0, os.getcwd())
9
# Importing from myproject.wsgi configures Django
10
from myproject.wsgi import application
11
# END DJANGO SETUP
12
13
# You can now import e.g. models from myapp
14
from myapp.models import MyModel
15
16
def main(params):
17
print(MyModel.objects.all())
In lines 4-10, we've added the current directory to the Python path, which allows us to import from e.g. myapp. This code assumes your working directory is your project root—Airplane will find requirements.txt to determine the project root and uses that as the working directory when running your task.
In line 14, you can see an example of importing a model—without the setup code, this normally fails.
You'll need to configure the task Environment Variables the same way you'd configure Django in production. For example, you should set DATABASE_URL if you need to connect to a database.
Finally, in line 17 you can use your model like you would in a normal Django handler.