Building a page with data

Most pages in a project need to present data that’s specific to the current user.

URL parameters

A URL often needs to accept a parameter telling it which data to access from the database. The second URL pattern shown here looks for the ID of a specific topic and stores it in the parameter topic_id.

urlpatterns = [
  url(r'^$', views.index, name='index'),
  views.topic, name='topic'),

Using data in a view

The view uses a parameter from the URL to pull the correct data from the database. In this example the view is sending a context dictionary to the template, containing data that should be displayed on the page.

def topic(request, topic_id):
  """Show a topic and all its entries."""
  topic = Topics.objects.get(id=topic_id)
  entries = topic.entry_set.order_by('-date_added')
  context = {
    'topic': topic,
    'entries': entries,
  return render(request,
    'learning_logs/topic.html', context)

Using data in a template

The data in the view function’s context dictionary is available within the template. This data is accessed using template variables, which are indicated by doubled curly braces. The vertical line after a template variable indicates a filter. In this case a filter called date formats date objects, and the filter linebreaks renders paragraphs properly on a web page

{% extends 'learning_logs/base.html' %}
{% block content %}
 <p>Topic: {{ topic }}</p>
 {% for entry in entries %}
 {{ entry.date_added|date:'M d, Y H:i' }}
 {{ entry.text|linebreaks }}
 {% empty %}
 <li>There are no entries yet.</li>
 {% endfor %}

{% endblock content %}

Template Inheritance

Template InheritanceMany elements of a web page are repeated on every page in the site, or every page in a section of the site. By writing one parent template for the site, and one for each section, you can easily modify the look and feel of your entire site.

The parent template

The parent template defines the elements common to a set of pages, and defines blocks that will be filled by individual pages

 <a href="{% url 'learning_logs:index' %}">
 Learning Log
{% block content %}{% endblock content %}

The child template

The child template uses the {% extends %} template tag to pull in the structure of the parent template. It then defines the content for any blocks defined in the parent template.

{% extends 'learning_logs/base.html' %}
{% block content %}
 Learning Log helps you keep track
 of your learning, for any topic you're
 learning about.
{% endblock content %}

Another model

A new model can use an existing model. The ForeignKey attribute establishes a connection between instances of the two related models. Make sure to migrate the database after adding a new model to your app.

Defining a model with a foreign key

class Entry(models.Model):
 """Learning log entries for a topic."""
  topic = models.ForeignKey(Topic)
  text = models.TextField()
  date_added = models.DateTimeField(

  def __str__(self):
    return self.text[:50] + "..."

Building a simple homepage

Users interact with a project through web pages, and a project’s home page can start out as a simple page with no data. A page usually needs a URL, a view, and a template.

Mapping a project’s URLs

The project’s main urls.py file tells Django where to find the urls.py files associated with each app in the project

from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
  url(r'^admin/', include(admin.site.urls)),
  url(r'', include('learning_logs.urls',

Mapping an app’s URLs

An app’s urls.py file tells Django which view to use for each URL in the app. You’ll need to make this file yourself, and save it in the app’s folder.

from django.conf.urls import url
from . import views
urlpatterns = [
  url(r'^$', views.index, name='index'),

Writing a simple view

A view takes information from a request and sends data to the browser, often through a template. View functions are stored in an app’s views.py file. This simple view function doesn’t pull in any data, but it uses the template index.html to render the home page

from django.shortcuts import render
def index(request):
  """The home page for Learning Log."""
  return render(request, 'learning_logs/index.html')

Writing a simple template

A template sets up the structure for a page. It’s a mix of html and template code, which is like Python but not as powerful. Make a folder called templates inside the project folder. Inside the templates folder make another folder with the same name as the app. This is where the template files should be saved

<p>Learning Log</p>
<p>Learning Log helps you keep track of your
learning, for any topic you're learning

Working with Model

Defining a model

To define the models for your app, modify the file models.py that was created in your app’s folder. The __str__() method tells Django how to represent data objects based on this model.

from django.db import models
class Topic(models.Model):
 """A topic the user is learning about."""
  text = models.CharField(max_length=200)
  date_added = models.DateTimeField(

  def __str__(self):
    return self.text

Activating a model

To use a model the app must be added to the tuple INSTALLED_APPS, which is stored in the project’s settings.py file.


  # My apps

Migrating the database

The database needs to be modified to store the kind of data that the model represents.

$ python manage.py makemigrations learning_logs 
$ python manage.py migrate

Creating a superuser

A superuser is a user account that has access to all aspects of the project.

$ python manage.py createsuperuser

Registering a model

You can register your models with Django’s admin site, which makes it easier to work with the data in your project. To do this, modify the app’s admin.py file. View the admin site at http://localhost:8000/admin/.

from django.contrib import admin
from learning_logs.models import Topic

Starting a Project

Create a virtual environment

$ virtualenv venv 
$ source venv/bin/activate

Install Django

$ pip install Django

Setup Django Project

$ django-admin.py startproject projectname

Create database

$ python manage.py syncdb

Run Server

$ python manage.py runserver

Create App

$ python manage.py startapp appname


Create Templates

$ mkdir appname/templates


dplyr cheat sheet is a quick reference for dplyr that is a grammar of data manipulation, providing a consistent set of verbs that help you solve the most common data manipulation challenges.


A regular expression is a sequence of characters that specifies a search pattern.


PySpark is an interface for Apache Spark in Python. It not only allows you to write Spark applications using Python APIs


Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson.


Watchman exists to watch files and record when they change. It can also trigger actions (such as rebuilding assets) when matching files change.


Rollup Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application.


Bluebird is a fully-featured Promise library for JavaScript. The strongest feature of Bluebird is that it allows you to "promisify" other Node modules in order to use them asynchronously. Promisify is a concept applied to callback functions.


Flow is a static type checker for your JavaScript code. It does a lot of work to make you more productive. Making you code faster, smarter, more confidently, and to a bigger scale.

Node.Js Api

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

C Preprocessor

Quick reference for the C macro preprocessor, which can be used independent of C/C++.


Sass is a preprocessor scripting language that is interpreted or compiled into Cascading Style Sheets. SassScript is the scripting language itself. Sass consists of two syntaxes.


Active Admin is a Ruby on Rails plugin for generating administration style interfaces. It abstracts common business application patterns to make it simple for developers to implement beautiful and elegant interfaces with very little effort.


The Fetch standard defines requests, responses, and the process that binds them: fetching.


$ http POST http://example.com name="John" Host:example.com — JSON, cookies, files, auth, and other httpie examples.


RSpec is a computer domain-specific language testing tool written in the programming language Ruby to test Ruby code. It is a behavior-driven development framework which is extensively used in production applications.


Sauce Labs allows users to run tests in the cloud on more than 700 different browser platforms, operating systems, and device combinations.


Jasmine is a behavior-driven development framework for testing JavaScript code.


Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server.


Ubuntu is a Linux distribution based on Debian and composed mostly of free and open-source software. Ubuntu is officially released in three editions: Desktop, Server, and Core for Internet of things devices and robots.

Rails Models

Ruby on Rails, or Rails, is a server-side web application framework written in Ruby under the MIT License. Rail is a model–view–controller framework, providing default structures for a database, a web service, and web pages.

Git Log

Git is software for tracking changes in any set of files, usually used for coordinating work among programmers collaboratively developing source code during software development.


Ruby on Rails, or Rails, is a server-side web application framework written in Ruby under the MIT License. Rails is a model–view–controller framework, providing default structures for a database, a web service, and web pages.

Ansible Examples

Ansible is an open-source software provisioning, configuration management, and application-deployment tool enabling infrastructure as code.

Bolt Quickstart

A quick guide to getting started writing Bolt tasks


RSpec Rails defines ten different types of specs for testing different parts of a typical Rails application.


rsync is a utility for efficiently transferring and synchronizing files between a computer and an external hard drive and across networked computers by comparing the modification times and sizes of files.

Ledger Cli

Ledger is a command-line based double-entry bookkeeping application. Accounting data is stored in a plain text file, using a simple format, which the users prepare themselves using other tools.


Homebrew is a free and open-source software package management system that simplifies the installation of software on Apple's operating system macOS as well as Linux.


Bundler provides a consistent environment for Ruby projects by tracking and installing the exact gems and versions that are needed.