Iterating Fast With Django & Heroku

Launching an online business can prove to be seriously complicated. Although on paper, it’s way easier to create an online business than a bricks-and-mortar one, an entrepreneur can get lost in the multitude of options. Some of the most common pitfalls an online entrepreneur gets stuck in include:

Iterating Fast With Django & Heroku

  • Building too much too early: Lose time and burn money building an intricate product. Get demotivated along the way, lose faith in the product, and abandon the project.
  • Believing too much in the idea: Getting stuck to the original idea and not iterating on it, even though customers don’t show up, don’t pay, or are not satisfied.
  • Failing to start: When somebody starts along the path of building a web project, he/she can get overwhelmed by the seemingly infinite decisions and choices that have to be made. What hosting to use? What platform? What WordPress theme? How to build a high-converting landing page? What programming language and what database? Should you use a web framework? Vanilla JavaScript or jQuery for the front end? Maybe a more complex front-end framework because the project will need one once it’s mature enough?
  • Failing to launch: When building a web project, even though you decided on your technology stack, you can get overwhelmed by the feedback you’re getting. Counterintuitively, it’s considered a mistake to listen to too much feedback. It can be the feedback from people that wouldn’t be using your product anyway. People tend to have an opinion about everything, even though they are not completely knowledgeable in the field.

Given the multitude of ways one can fail along the road, it’s really important to:

  • Build as little and as quickly as possible, showing it to people who you consider to be potential customers: Minimise costs and effort.
  • Put it online as soon as possible: Get feedback from people on the product, not on your abstract idea.
  • Make changes quickly: When learning what the customer wants, it’s crucial to be agile and serve your first paying customers well.

Here’s where prototyping comes into place. An entrepreneur should run lean, not wasting time and resources. Building as little as possible at the beginning can prove a virtue.

There are many schools of thought on what a prototype is and how it should be created. Some say that it should be only a landing page, others that it should be a stripped-down version of the final product. I’m more of a fan of the second. Using only a landing page can feel scammy. Also, you can’t get feedback on how you are solving the problem, but rather only on if the problem is worth solving.

Here’s the toolbelt of a smart prototyping online entrepreneur:

  • Front-End Frameworks: Bootstrap, Foundation, jQuery, Vue, etc. Using a front-end framework will make your apps work on different screen sizes and different browsers, with a decent design.
  • Back-End Frameworks: Django, Ruby on Rails, Laravel. Using back-end frameworks will help you easily deal with HTML templates, HTTP forms, database access, URL schemas, etc.
  • Platform-as-a-Service: Heroku, Google App Engine, AWS Elastic Beanstalk. Choosing a PaaS can free you from the pain of managing servers, log aggregation, uptime monitoring, deployment infrastructure and more.

In this tutorial, we’ll be building a simple application in the spirit of rapid prototyping. We’ll be using Django, Bootstrap CSS, and Heroku. The focus will be on the back-end part rather than the front end.

We’re going to take advantage of the Heroku platform to put something online early and to quickly deploy new features. We’re going to use Django to build complex database models and functionality. Bootstrap CSS will give us a sensible default style for our pages. Enough talking, let’s go.

What We’re Building

Make sure you’re sitting down for this one. The idea will knock your socks off. Here’s the pitch: Don’t you just hate how you get all these discount codes but you forget to use them and they expire?

Wouldn’t it be cool to store the codes somewhere where you can search them and also be notified when they’re about to expire? I know, great idea, right? Well, put your credit card down, you won’t be investing in this one. You’re going to build it.

Getting Started

In this tutorial, I’m going to use Python 3. If you are using Python 2.7, the changes should be fairly easy. I’m also going to assume that you’re familiar with setuptools, Python virtualenvs, and Git. One more thing before going forward: make sure you have a GitHub and a Heroku account. To use Heroku, you also need to install the Heroku CLI.

Let’s start by creating a virtualenv:

$ mkvirtualenv coupy

As you’ve probably figured out, our application name is Coupy. Let’s switch to the new virtualenv, $ workon coupy, and install Django:

$ pip install Django

Go into your GitHub account and create a new project. Next, let’s clone that project:

$ git clone https://github.com/<GITHUB_USERNAME>/<GITHUB_PROJECT_NAME>.git
$ cd <GITHUB_PROJECT_NAME>

The next logical step is to create a Django project. To deploy a Django project to Heroku, we need to follow some guidelines. Fortunately, we can use a project template for that. Here’s how to do that:

$ django-admin.py startproject --template=https://github.com/heroku/heroku-django-template/archive/master.zip --name=Procfile coupy

You might need to move around some folders. Make sure your repository root folder looks like this:

.
├── Procfile
├── README.md
├── coupy
│   ├── __init__.py
│   ├── settings.py
│   ├── static
│   │   └── humans.txt
│   ├── urls.py
│   └── wsgi.py
├── manage.py
├── requirements.txt
└── runtime.txt

Let’s now install the requirements provided by the template:

$ pip install -r requirements.txt

We now want to push the newly created files to GitHub:

$ git add .
$ git commit -m"Init Django project"
$ git push origin master

Let’s see if what we’ve done so far works:

$ python manage.py runserver

Now open a browser window and go to http://localhost:8000. If all is good, you should see the classic Django Welcome page. To make sure that all is good from Heroku’s perspective, we can also run the application like this:

$ heroku local web

To prove how quickly we can go online, let’s make our first deploy to Heroku:

$ heroku login
$ heroku create

We have now created a Heroku application, but we haven’t sent any code to Heroku. Notice that Heroku created a user-friendly app id. Here’s the output you should get:

Creating app... done, ⬢ <HEROKU_APP_ID>
https://<HEROKU_APP_ID>.herokuapp.com/ | https://git.heroku.com/<HEROKU_APP_ID>.git

We now need to associate our repo with the newly created Heroku app:

$ heroku git:remote -a <HEROKU_APP_ID>
$ git push heroku master
$ heroku open

Awesome, you just deployed an app to Heroku. It doesn’t do much, but you put something online in record time. Good job.

Setting Up the Database

You probably won’t ever build a non-trivial web app without a database. The database is the data storage part of the web app. Here’s where the web app keeps its state (at least most of it). Here’s where we keep the user accounts and the login details and much, much more. Heroku provides a managed PostgreSQL service.

That’s what we’re going to use. Make sure you have installed Postgres on your machine and create a database instance to use in our application. Heroku needs an environment variable to be set to be able to connect to the database service. The variable we need to set is DATABASE_URL:

$ export DATABASE_URL="postgres://<USERNAME>:<PASSWORD>@localhost:5432/<DATABASE_NAME>"

Let’s now tell Django to apply the migrations and create the necessary tables:

$ ./manage.py migrate

Let’s create a superuser and login to the admin interface at http://localhost:8000/admin:

$ ./manage.py createsuperuser
$ ./manage.py runserver

We can see that the tables have indeed been created. Heroku already associated a database instance to your app by default. You can make sure that’s the case by checking in Heroku HEROKU_APP_ID > Settings > Config Variables in your Heroku online console. You should see here that the DATABASE_URL is set to a Heroku generated database address.

We now have to run the migrations and create the super user commands online. Let’s see if it all works as expected:

$ heroku run python manage.py migrate
$ heroku run python manage.py createsuperuser

If all went well, if we visit https://<HEROKU_APP_ID>.herokuapp.com/admin/, we should be able to log in with the credentials we just provided.

User Authentication

In this section, we’re going to initialize a Django app and use Django predefined components to create the user authentication functionality in our app.

$ ./manage.py startapp main

Inside the new app, we’re going to create a urls.py file:

from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.views.generic.base import RedirectView


urlpatterns = [
    url('^$', RedirectView.as_view(url='login'), name='index'),
    url(r'^login$', auth_views.LoginView.as_view(), name='login'),
    url(r'^logout$', auth_views.LogoutView.as_view(), name='logout'),
]

Here we use three generic Django views:

  • RedirectView: Since the base URL of the application doesn’t do anything, we’re redirecting to the login page.
  • LoginView: Django predefined view that creates the login form and implements the user authentication routine.
  • LogoutView: Django predefined view that logs a user out and redirects to a certain page.

Add the main application to the INSTALLED_APPS list:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    # Disable Django's own staticfiles handling in favour of WhiteNoise, for
    # greater consistency between gunicorn and `./manage.py runserver`. See:
    # http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',

    'main',
]

Hook up the main.urls to the root URL schema:

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^', include('main.urls')),
    url(r'^admin/', admin.site.urls),
]

In order to display the forms properly, with styles and classes and everything, we need to install django-widget-tweaks:

$ pip install django-widget-tweaks
$ pip freeze > requirements.txt

Add django-widget-tweaks to INSTALLED_APPS:

INSTALLED_APPS = [
    # ...
    'main',
    'widget_tweaks',
]

We now add these two configs to settings.py:

  • LOGIN_REDIRECT_URL: Tells Django where to redirect a user after a successful authentication.
  • LOGOUT_REDIRECT_URL: Tells Django where to redirect the user after he/she logs out.
# settings.py

LOGIN_REDIRECT_URL = 'dashboard'
LOGOUT_REDIRECT_URL = 'login'

Let’s write a simple master template base.html and a dashboard.html template that extends it. We’ll get back to the dashboard one later.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <div class="container">
    {% block content %}{% endblock %}
    </div><!-- /container-->
</body>
</html>
{% extends 'base.html' %}

{% block title %}Dashboard{% endblock %}

{% block content %}
<h1>Dashboard</h1>
{% endblock %}

Write the view that renders the dashboard.html template:

from django.shortcuts import render
from django.core.urlresolvers import reverse_lazy


@login_required(login_url=reverse_lazy('login'))
def dashboard(request):
    return render(request, 'dashboard.html')

We’re all set. Head over to http://localhost:8000/login/ and test that authentication works. Next, save your progress:

$ git add .
$ git commit -m"Login/Logout/Dashboard views"

Create the Coupon Model

Now we’ve come to the most important part of our application, designing the Coupon model. We’ll be installing django-model-utils to add some extra properties to our models.

$ pip install django-model-utils
$ pip freeze > requirements.txt

Write the Coupon model:

from model_utils.models import TimeStampedModel, TimeFramedModel
from django.db import models
from django.contrib.auth.models import User


class Coupon(TimeStampedModel, TimeFramedModel):
    owner = models.ForeignKey(User)
    discount_code = models.CharField("Discount Code", max_length=100)
    website = models.URLField("Website")
    description = models.TextField("Coupon Description")

The django-model-utils models we extended enable us to:

  • TimeStampedModel helps us track when the model was placed in the database, via the created field.
  • TimeFramedModel adds the start and end fields to our model. We’re using these fields to keep track of the coupon’s availability.

Hook the model to the admin:

from django.contrib import admin
from .models import Coupon


@admin.register(Coupon)
class CouponAdmin(admin.ModelAdmin):
    pass

Create and apply migrations:

$ ./manage.py makemigrations
$ ./manage.py migrate

Save progress:

$ git add .
$ git commit -m"Create Coupon model"

ModelForm for Coupon Creation

One of the cool features of Django is the ability to create forms from model classes. We’re going to create such a form that enables users to create coupons. Let’s create a forms.py file inside the main application:

from django.forms import ModelForm
from .models import Coupon


class CouponForm(ModelForm):
    class Meta:
        model = Coupon
        exclude = ('owner', ) # We're setting this field ourselves

Let’s add this form to the dashboard. We need to change both the view and the template:

# views.py

from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse_lazy
from .forms import CouponForm


@login_required(login_url=reverse_lazy('login'))
def dashboard(request):
    if request.method == 'POST':
        form = CouponForm(request.POST)
        if form.is_valid():
            coupon = form.save(commit=False)
            coupon.owner = request.user
            coupon.save()
            return redirect('dashboard')
    else:
        form = CouponForm()

    return render(request, 'dashboard.html', context={'create_form': form})
{% extends 'base.html' %}

{% load widget_tweaks %}

{% block title %}Dashboard{% endblock %}

{% block content %}
<h1>Dashboard</h1>

<form method="post">
    {% csrf_token %}
    <div class="form-group">
        <label for="discount_code">Discount Code</label>
        {% render_field create_form.discount_code class="form-control" placeholder="Discount Code" %}
    </div>

    <div class="form-group">
        <label for="website">Website</label>
        {% render_field create_form.website class="form-control" placeholder="Website" %}
    </div>

    <div class="form-group">
        <label for="description">Description</label>
        {% render_field create_form.description class="form-control" placeholder="Description" %}
    </div>

    <div class="form-group">
        <label for="start">Available From</label>
        {% render_field create_form.start class="form-control" placeholder="Available From (MM/DD/YYYY)" %}
    </div>

    <div class="form-group">
        <label for="end">Expires on</label>
        {% render_field create_form.end class="form-control" placeholder="Expires On (MM/DD/YYYY)" %}
    </div>

    <button type="submit" class="btn btn-primary">Save</button>
</form>


{% endblock %}

We now have a way to create coupons from the dashboard. Go give it a try. We have no way of seeing the coupons in the dashboard, but we can do so in the admin panel. Let’s save the progress:

$ git add .
$ git commit -m"Coupon creation form in dashboard"

Expiring Soon Coupons

One more thing we want to be displayed in the dashboard: coupons that expire soon, for example ones that expire this week.

Add django.contrib.humanize to INSTALLED_APPS to display dates in the templates in a human-friendly way.

Let’s enhance the view so that it fetches the soon expiring coupons and passes them to the template context:

from datetime import timedelta

from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse_lazy
from django.utils import timezone

from .forms import CouponForm
from .models import Coupon


@login_required(login_url=reverse_lazy('login'))
def dashboard(request):
    expiring_coupons = Coupon.objects.filter(
        end__gte=timezone.now(),
        end__lte=timezone.now() + timedelta(days=7))

    if request.method == 'POST':
        form = CouponForm(request.POST)
        if form.is_valid():
            coupon = form.save(commit=False)
            coupon.owner = request.user
            coupon.save()
            return redirect('dashboard')
    else:
        form = CouponForm()

    return render(request, 'dashboard.html', context={
        'create_form': form,
        'expiring_coupons': expiring_coupons})

Let’s update the template so that it displays the expiring coupons in a tabular way. We’ll also put the creation form and the table in two separate columns using Bootstrap’s grid system:

{% extends 'base.html' %}

{% load widget_tweaks %}
{% load humanize %}

{% block title %}Dashboard{% endblock %}

{% block content %}
<h1>Dashboard</h1>
<div class="row">
    <div class="col-md-6">
        [The form code]
    </div>
    <div class="col-md-6">
        {% if expiring_coupons %}
            <table class="table">
                <thead>
                    <tr>
                        <th>Discount Code</th>
                        <th>Website</th>
                        <th>Expire Date</th>
                    </tr>
                </thead>
            {% for coupon in expiring_coupons %}
                <tr>
                    <td>{{coupon.discount_code}}</td>
                    <td>{{coupon.website}}</td>
                    <td>{{coupon.end|naturalday }}</td>
                </tr>
            {% endfor %}
            </table>
        {% else %}
            <div class="alert alert-success" role="alert">No coupons expiring soon</div>
        {% endif %}

        {% endblock %}
    </div>
</div>

Looking good. Save your progress:

$ git add .
$ git commit -m"Implementing the expiring coupon list"

Catalogue View

Let’s now learn some other Django shortcuts to create a view that displays the list of coupons we have available. We’re talking about generic views. Here’s how to quickly create a ListView:

# views.py

# ...
from django.views.generic.list import ListView
from django.db.models import Q


class CouponListView(ListView):
    model = Coupon

    def get_queryset(self):
        return Coupon.objects.filter(Q(end__gte=timezone.now()) | Q(end__isnull=True)).order_by('-end')

Now tie the view in your URL schema:

# main/urls.py

from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.views.generic.base import RedirectView
from .views import dashboard, CouponListView


urlpatterns = [
    url('^$', RedirectView.as_view(url='login'), name='index'),
    url(r'^login/$', auth_views.LoginView.as_view(), name='login'),
    url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'),
    url(r'^dashboard/$', dashboard, name='dashboard'),
    url(r'^catalogue/$', CouponListView.as_view(template_name='catalogue.html'), name='catalogue'),

]

Create the template catalogue.html:

{% extends 'base.html' %}

{% load humanize %}

{% block title %}Catalogue{% endblock %}

{% block content %}
<h1>Catalogue</h1>
<div class="row">

    <div class="col-md-12">
        {% if object_list %}
            <table class="table">
                <thead>
                    <tr>
                        <th>Discount Code</th>
                        <th>Website</th>
                        <th>Expire Date</th>
                    </tr>
                </thead>
            {% for coupon in object_list %}
                <tr>
                    <td>{{coupon.discount_code}}</td>
                    <td>{{coupon.website}}</td>
                    <td>{{coupon.end|naturalday }}</td>
                </tr>
            {% endfor %}
            </table>
        {% else %}
            <div class="alert alert-success" role="alert">
                No coupons yet. Create your first one <a href="{% url 'dashboard' %}">here</a>.
            </div>
        {% endif %}

        {% endblock %}
    </div>
</div>

Since we’ve hooked everything up, head over to http://localhost:8000/catalogue/ to view your coupon catalogue.

Save the progress:

$ git add .
$ git commit -m"Creating the catalogue view"

This is pretty close to an MVP. I encourage you to do some fine tuning like creating a navbar, login/logout/register buttons, etc. The important thing is that you understand the process of prototyping and getting your product out there for people to see it. Speaking of which, our product is not online yet. We didn’t push the latest version to Heroku. Let’s do that and then pick up the phone and call the investors.

Conclusion

We created a simple but practical application. We created features quickly, and we’ve deployed them online so that our potential customers can use them and give us feedback. It’s better to show people rather than only talk about an idea.

Here are some conclusions we can draw:

  • Picking the right tools can significantly speed up the development process.
  • The tools used for prototyping aren’t always the best choice for more mature projects. Keeping that in mind, it’s better to use more agile tools early on and iterate on them rather than getting lost in minute implementation details early on.
  • Taking advantage of a PaaS means that the applications have to respect a few design patterns. Usually these patterns make sense, and they force us to write even better code.
  • Django has a lot of shortcuts that make our lives easier:
    • Django ORM helps with database access. No need to worry about writing correct SQL and being extra careful with syntax errors.
    • Migrations help us version and iterate on the database schema. No need to go and write SQL to create tables or add columns.
    • Django has a plugin-friendly architecture. We can install apps that help us achieve our goals quicker.
    • Generic views and model forms can inject some of the most common behaviors: listing models, creating models, authentication, redirection, etc.
  • When launching, it’s important to be lean and fast. Don’t waste time, and don’t spend money.