Using Python's Django framework in the cloud

scosta

Saul Costa

Posted on May 21, 2019

Using Python's Django framework in the cloud

Django is a Python framework for building web apps. Their website describes it like so:

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It's free and open source.

In this post, we'll cover how to use the Next Sandbox to get started with Django without downloading anything! We'll walk through how you can launch a Python sandbox and then install Django in it.

First, click here to launch a Python sandbox (you'll need to create a free Next Tech account if you haven't already).

Once your sandbox has loaded, run the following commands in your sandbox's terminal to install Django:

sudo apt update
sudo apt install -y python3-django

Then, create a new Django project:

django-admin startproject project .

Now you can run the initial Django migrations:

python3 manage.py migrate

Migrations in Django are explained in detail here.

To start the Django web server, run the following in your terminal:

python3 manage.py runserver 0.0.0.0:8000

Note the use of the 0.0.0.0:8000. This is required to allow remote connections, which you will technically be making to your sandbox.

You'll also need to make some changes to the project/settings.py file. First, replace the contents of the MIDDLEWARE list with this:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware'
]

This removes an option added by default that prevents your webpage from being embedded, which it needs to be so the in-sandbox web browser can load it.

Then, you need add this line to the file:

ALLOWED_HOSTS = ['*']

This will allow any host to connect so the domain your sandbox is running on will be able to.

This part of your file should now look something like this:

Okay, all set! Now, click the + and select a browser, then enter localhost:8000 in the URL bar. You'll be shown this:

Great work! You can now continue to explore Django. I recommend reading through the Django Quick Start guide, which covers some of what we have in this post, and much more!

Have a question or comment? Drop us a note below!

💖 💪 🙅 🚩
scosta
Saul Costa

Posted on May 21, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related