Running Django on the App Engine standard environment

Django apps that run on App Engine standard environment scale dynamically according to traffic.

This tutorial assumes that you're familiar with Django web development. If you're new to Django development, it's a good idea to work through writing your first Django app before continuing. In that tutorial, the app's models represent polls that contain questions, and you can interact with the models by using the Django admin console.

This tutorial requires Python 3.7.

Before you begin

Check off each step as you complete it.

  1. check_box_outline_blank check_box Create a project in the Google Cloud Platform Console.
    If you haven't already created a project, create one now. Projects enable you to manage all Google Cloud Platform resources for your app, including deployment, access control, billing, and services.
    1. Open the GCP Console.
    2. In the drop-down menu at the top, select Create a project.
    3. Click Show advanced options. Under App Engine location, select a United States location.
    4. Give your project a name.
    5. Make a note of the project ID, which might be different from the project name. The project ID is used in commands and in configurations.
  2. check_box_outline_blank check_box Enable billing for your project, and sign up for a free trial.

    If you haven't already enabled billing for your project, enable billing now, and sign up for a free trial. Enabling billing allows the app to consume billable resources such as running instances and storing data. During your free trial period, you won't be billed for any services.

  3. check_box_outline_blank check_box Install the Cloud SDK.

    If you haven't already installed the Cloud SDK, install and initialize the Cloud SDK now. The Cloud SDK contains tools and libraries that enable you to create and manage resources on GCP.

  4. check_box_outline_blank check_box Enable APIs for your project.

    This takes you to the GCP Console and automatically enables the APIs used by this tutorial. The APIs used are: Cloud SQL Admin API.

Log in to gcloud

Acquire new credentials to use the Cloud SQL Admin API:

gcloud auth application-default login

Downloading and running the app

After you've completed the prerequisites, download and deploy the Django sample app. The following sections guide you through configuring, running, and deploying the app.

Cloning the Django app

The code for the Django sample app is in the GoogleCloudPlatform/python-docs-samples repository on GitHub.

  1. You can either download the sample as a zip file and extract it or clone the repository to your local machine:

    git clone

  2. Go to the directory that contains the sample code:


    cd python-docs-samples/appengine/standard_python37/django


    cd python-docs-samples\appengine\standard_python37\django

Setting up your local environment

When deployed, your app uses the Cloud SQL Proxy that is built in to the App Engine environment to communicate with your Cloud SQL instance. However, to test your app locally, you must install and use a local copy of the proxy in your development environment.

Learn more about the Cloud SQL Proxy.

To perform basic admin tasks on your Cloud SQL instance, you can use the MySQL client.

Enable the Cloud SQL Admin API

Before using Cloud SQL, you must enable the Cloud SQL Admin API:

gcloud services enable sqladmin

Installing the Cloud SQL Proxy

Download and install the Cloud SQL Proxy. The Cloud SQL Proxy connects to your Cloud SQL instance when running locally.

Linux 64-bit

  1. Download the proxy:
    wget -O cloud_sql_proxy
  2. Make the proxy executable:
    chmod +x cloud_sql_proxy

Linux 32-bit

  1. Download the proxy:
    wget -O cloud_sql_proxy
  2. Make the proxy executable:
    chmod +x cloud_sql_proxy

macOS 64-bit

  1. Download the proxy:
    curl -o cloud_sql_proxy
  2. Make the proxy executable:
    chmod +x cloud_sql_proxy

macOS 32-bit

  1. Download the proxy:
    curl -o cloud_sql_proxy
  2. Make the proxy executable:
    chmod +x cloud_sql_proxy

Windows 64-bit

Right-click and select Save Link As to download the proxy. Rename the file to cloud_sql_proxy.exe.

Windows 32-bit

Right-click and select Save Link As to download the proxy. Rename the file to cloud_sql_proxy.exe.
If your operating system isn't included here, you can also compile the proxy from source.

Creating a Cloud SQL instance

  1. Create a Cloud SQL for MySQL Second Generation instance.

    Name the instance polls-instance or similar. It can take a few minutes for the instance to be ready. When the instance is ready, it's visible in the instances list.

  2. Use the Cloud SDK to run the following command where [YOUR_INSTANCE_NAME] represents the name of your Cloud SQL instance:
    gcloud sql instances describe [YOUR_INSTANCE_NAME]

    In the output, note the value shown for [CONNECTION_NAME].


Initializing your Cloud SQL instance

  1. Start the Cloud SQL Proxy by using the [CONNECTION_NAME] value from the previous step:


    ./cloud_sql_proxy -instances="[YOUR_INSTANCE_CONNECTION_NAME]"=tcp:3306


    cloud_sql_proxy.exe -instances="[YOUR_INSTANCE_CONNECTION_NAME]"=tcp:3306

    Replace [YOUR_INSTANCE_CONNECTION_NAME] with the [CONNECTION_NAME] value that you recorded in the previous step.

    This step establishes a connection from your local computer to your Cloud SQL instance for local testing purposes. Keep the Cloud SQL Proxy running the entire time you test your app locally.

  2. Create a Cloud SQL user and database:

    GCP Console

    1. Create a new database by using the GCP Console for your Cloud SQL instance polls-instance. For example, you can use the name polls.
    2. Create a new user by using the GCP Console for your Cloud SQL instance polls-instance.

    MySQL client

    1. In a separate command-line tab, use the MySQL client or similar program to connect to your instance. When prompted, use the root password you configured.
      mysql --host --user root --password
    2. Create the required databases, users, and access permissions in your Cloud SQL database using the following commands. Replace [MYSQL_USER] and [MYSQL_PASSWORD] with the username and password you want to use.
      CREATE DATABASE polls;

Configuring the database settings

  1. Open mysite/ for editing.

    1. To help set up the connection to the database for both App Engine deployment and local testing, set <your-database-user> and <your-database-password> to the username and password you created previously in the step Creating a Cloud SQL instance.

    2. Get the values for your instance:

      gcloud sql instances describe [YOUR_INSTANCE_NAME]
    3. From the output, copy the connectionName value for use in the next step.

    4. Set <your-cloudsql-connection-string> to the connectionName from the previous step.

    5. Set [YOUR-DATABASE] to the name you chose during the Initialize your Cloud SQL instance step.

  2. Close and save

Running the app on your local computer

  1. To run the Django app on your local computer, set up a Python development environment, including Python, pip, and virtualenv.

  2. Create an isolated Python environment, and install dependencies:


    virtualenv env
    source env/bin/activate
    pip install -r requirements.txt


    virtualenv env
    pip install -r requirements.txt

  3. Run the Django migrations to set up your models:

    python makemigrations
    python makemigrations polls
    python migrate
  4. Start a local web server:

    python runserver
  5. In your browser, go to http://localhost:8000:


    The page displays the following text: "No polls are available." The Django web server running on your computer delivers the sample app pages.

  6. Press Control+C to stop the local web server.

Using the Django admin console

  1. Create a superuser. You need to define a username and password.

    python createsuperuser
  2. Start a local web server:

    python runserver
  3. In your browser, go to http://localhost:8000/admin.

  4. Log in to the admin site using the username and password you used when you ran createsuperuser.

Deploying the app to the App Engine standard environment

  1. Gather all the static content into one folder by moving all of the app's static files into the folder specified by STATIC_ROOT in

    python collectstatic
  2. Upload the app by running the following command from within the python-docs-samples/appengine/standard/django directory of the app where the app.yaml file is located:

    gcloud app deploy

    Wait for the message that notifies you that the update has completed.

Seeing the app run in GCP

The following command deploys the app as described in app.yaml and sets the newly deployed version as the default version, causing it to serve all new traffic.

  • In your browser, enter the following address. Replace <your-project-id> with your GCP project ID.


Your request is served by a web server running in the App Engine standard environment.

If you update your app, you deploy the updated version by entering the same command that you used to deploy the app. The deployment creates a new version of your app and promotes it to the default version. The earlier versions of your app remain. All of these app versions are billable resources. To reduce costs, delete the non-default versions of your app.

For information about deleting the non-default versions of your app, see Cleaning up.


When you are ready to serve your content in production, in mysite/, change the DEBUG variable to False.

Understanding the code

The Django sample app was created using standard Django tooling.

  • The following commands create the project and the polls app:

    django-admin startproject mysite
    python startapp polls
  • The file contains the configuration for your SQL database. The code in uses the GAE_APPLICATION environment variable to determine whether the app is running on App Engine or running on your local computer:

    • When the app runs on App Engine, it connects to the MySQL host by using the /cloudsql Unix socket.
    • When the app runs on your local computer, it connects to the MySQL host by using TCP, which requires a username and password.
    if os.getenv('GAE_APPLICATION', None):
        # Running on production App Engine, so connect to Google Cloud SQL using
        # the unix socket at /cloudsql/<your-cloudsql-connection string>
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'HOST': '/cloudsql/[YOUR-CONNECTION-NAME]',
                'USER': '[YOUR-USERNAME]',
                'PASSWORD': '[YOUR-PASSWORD]',
                'NAME': '[YOUR-DATABASE]',
        # Running locally so connect to either a local MySQL instance or connect to
        # Cloud SQL via the proxy. To start the proxy via command line:
        #     $ cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:3306
        # See
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'HOST': '',
                'PORT': '3306',
                'NAME': '[YOUR-DATABASE]',
                'USER': '[YOUR-USERNAME]',
                'PASSWORD': '[YOUR-PASSWORD]',
  • The app.yaml file contains configuration information for deployment to App Engine. This app.yaml file specifies that App Engine serves static files from the static/ directory:

    runtime: python37
    # This configures Google App Engine to serve the files in the app's static
    # directory.
    - url: /static
      static_dir: static/
    # This handler routes all requests not caught above to your main app. It is
    # required when static routes are defined, but can be omitted (along with
    # the entire handlers section) when there are no static files defined.
    - url: /.*
      script: auto
Was this page helpful? Let us know how we did:

Send feedback about...