Django or Rails: two answers to the same question

TL;DR

Difficulty: Beginner

Django and Rails are both mature, open source, batteries included frameworks, and for a typical business application their features are close.

  • The real difference is where each keeps its knowledge: Rails in shared convention, Django in your project's files.
  • Built twice, the same booking feature takes 53 lines in Rails 7.1 and 49 in Django 5.0, but wiring is 1.9% of the Rails lines and 22.4% of the Django lines.
  • Rails treats the database as the source of truth for your data, Django treats the model class as the source of truth.
  • Rule of thumb: a Rails application is easiest to read for someone who knows Rails, a Django project for someone who knows Python.

Django and Rails make the same promise: build a serious web application quickly, with one framework that already does the common work. So what is actually different? This chapter answers from each framework's own documentation, with one small feature built in both, side by side.

The question behind this article

Django and Ruby on Rails make the same promise. Both say you can build a serious web application quickly, with one framework that already knows how to talk to a database, show pages, handle forms and keep the obvious attacks out. Both are open source, both are mature, and both run large products. So if you are choosing between them, or paying someone who is, the honest question is a simple one: what is actually different?

Most comparisons answer with a feature checklist. Admin panel here, background jobs there, a benchmark somewhere in the middle. That misses the point, because at the level of features the two frameworks are closer than their fans admit. The real difference sits one layer down, in how each one wants you to think. This article shows that difference in plain words and in real code, using the same small feature built twice.

I should say where I stand before I start. I build web applications and online shops on Ruby on Rails, so I have a side, and you should read everything here knowing that. I do not build Django applications for clients. What I can do is compare the two fairly, from their own documentation, in a way a senior Django developer would sign off on. That is the standard I hold this whole series to.

This is the first of six chapters on choosing between Django and Rails. Here I explain the two philosophies. The next chapters cover where each framework genuinely shines, how long each takes to learn, what each costs to run and hire for, what five years of upgrades look like, and finally a decision method you can use on your own project.

Example: Freewheel Cycles and its two developers

Throughout the series I use one invented business. Freewheel Cycles runs six bicycle repair workshops around Limerick (freewheelcycles.example). Its founder, Niamh, wants to replace a tangle of spreadsheets and a rented booking widget with her own web application. The numbers she gives:

  • six workshops and 38 mechanics,
  • about 1,150 repair bookings a week, with 30% of the week's online bookings arriving between Friday 6pm and Saturday noon,
  • 9,000 active customers and 2,400 spare parts in stock,
  • an average repair of €95 at a labour rate of €52 an hour.

The application has to take online bookings with a time slot per mechanic, run a live workshop board where job cards move from "waiting" to "in repair" to "ready", store before and after photos, track parts with a nightly reorder report, send "your bike is ready" by email and SMS, give managers a back office, produce invoices with VAT, and report on all of it. Later it needs a small app for mechanics and a demand forecast for parts.

Niamh has two developers. Aisling has four years of Python, mostly data analysis and a little Flask. Cian has three years of JavaScript and TypeScript with React. Neither has written Ruby. The budget for the first version is six months. Freewheel, Niamh, Aisling and Cian are all made up. The code in this article is real and runs on the versions current as I write, in December 2023: Rails 7.1 and Django 5.0.

The short answer: where each framework keeps its knowledge

Every web application needs hundreds of small connections. This address goes to that code. This class reads that table. This page uses that template. A framework is, to a large extent, a way of deciding where those connections are written down.

Here is the model I use, and the one idea I would like you to take away if you read nothing else:

  • Rails keeps the connections in shared convention. Name things the Rails way and the framework connects them for you. The knowledge lives in the framework and in the heads of everyone who knows Rails, so it is the same in every Rails application.
  • Django keeps the connections in your project's files. You write most of them down, in Python, where anyone can read them. The knowledge lives in the repository, so a Python developer who has never seen Django can follow the wiring by reading.

Neither is free. Shared convention means less to write and less to read, but only once you know the convention: until then, things happen for reasons you cannot see on the page. Written connections mean a little more to write and more to read, but nothing is hidden from a careful reader of that project.

This gives a rule of thumb I find more useful than any feature table: a Rails application is easiest to read for someone who knows Rails, and a Django project is easiest to read for someone who knows Python. Everything else in this article is that sentence, worked through.

On Freewheel's booking list there is a link to the "new booking" form. In the Rails version the link's address comes from a method called new_booking_path. Search the whole project for def new_booking_path and you will find nothing. The method exists because one line in the routes file, resources :bookings, tells Rails to generate it, following a naming rule you are expected to know.

In the Django version the same link uses the name "bookings:new". Search the project for name="new" and you find the exact line in bookings/urls.py that defines it, next to app_name = "bookings". Nothing to know in advance, only something to read.

Both links work. Both are safe. The difference is where the knowledge lives.

Two frameworks extracted from real products

Neither framework was designed in a vacuum. Both were pulled out of working software, and that origin explains a lot about how they feel.

Rails came from Basecamp, the project management product of the company 37signals. David Heinemeier Hansson built Rails while building Basecamp, and the Rails website of 2005 described Basecamp as "the original Rails application"1. Rails was first released as open source in 20042, reached version 1.0 on 13 December 20053, and is published under the MIT licence4.

Django came from a newsroom. The Django documentation tells the story itself: World Online, the web department of a newspaper in Lawrence, Kansas, had to build web applications on journalism deadlines, sometimes from concept to launch in hours. In autumn 2003 its developers Adrian Holovaty and Simon Willison moved from PHP to Python and began extracting a generic framework from their work. In summer 2005 World Online released it as open source, under the name Django, after the jazz guitarist Django Reinhardt. It is distributed under the three clause BSD licence5.

Both frameworks are what people call "batteries included": they ship with most of what a typical web application needs, so you do not assemble a stack from dozens of separate libraries. Django says so in its own documentation, borrowing the phrase from Python6. Rails puts the same idea differently, as the next section shows.

Example: what extraction would mean at Freewheel

Imagine Aisling builds Freewheel's booking system and, after a year, notices she has written the same three things five times: a list page, a form that validates and saves, and a redirect with a confirmation message. She pulls them into one reusable piece of code, so the sixth page takes ten minutes instead of a morning. That reusable piece is a tiny framework, extracted from her product.

Rails and Django are that process run for years, on real products, by people under real deadlines. It is why both feel practical rather than academic, and why both are at their best when the thing you build looks a bit like the thing they came from: a database backed application with pages, forms and users. Freewheel's application is exactly that.

The two philosophies, in their own words

Each framework has written down what it believes. Reading the originals is the fastest way to understand why the code looks the way it does.

Rails: the doctrine

In 2016 David Heinemeier Hansson published The Rails Doctrine, nine pillars that describe how Rails is designed7. Four of them matter most for this comparison:

  • Programmer happiness. The first pillar asks Rails to optimise for the programmer's happiness, a value it inherits from Ruby, whose creator put the programmer's experience first. The doctrine is open that this is a subjective goal and defends it anyway.
  • Convention over configuration. The doctrine opens this pillar with an old Rails motto, "You're not a beautiful and unique snowflake". The argument: thousands of small decisions, like what to call a primary key, are not worth making again in every project. Agree on them once, and spend your attention on what is unique about your application.
  • The menu is omakase. In a Japanese restaurant, omakase means the chef chooses. Rails chooses the libraries and how they fit together, for example the front end tools and the test framework, and you can substitute them but do not have to.
  • Value integrated systems. Rails is built for one complete application, front end to database migrations, what the doctrine calls a majestic monolith, rather than a system split early into many small services.

The doctrine also names the cost of convention honestly. Most applications have some part that is genuinely unusual, and the hard skill is knowing when to step off the conventions and when you are just being a snowflake.

Django: the Zen of Python and the design philosophies

Python has its own short creed, PEP 20, written by Tim Peters in 2004 and known as the Zen of Python8. Its 19 short aphorisms include "Explicit is better than implicit." and the line that there should be one, and preferably only one, obvious way to do something.

Django builds on that. Its documentation has a page called Design philosophies that explains the framework's choices9. The overall principles are loose coupling, less code, quick development, Don't Repeat Yourself (DRY), explicit is better than implicit, and consistency. The page is precise about what "explicit" means for Django: "Magic shouldn't happen unless there's a really good reason for it." It also asks the framework, within reason, to work out as much as it can from very little input. That matters later in this article, because it means Django infers things too.

Two more principles from that page shape everyday work. Loose coupling: the template system knows nothing about web requests, and the database layer knows nothing about how data is displayed, so each layer can be swapped. And the template language deliberately stays small, enough logic for presentation and no more, so a template cannot run arbitrary Python.

Example: one security feature, two philosophies

Both frameworks protect forms against cross site request forgery (CSRF), an attack where another website tricks a logged in user's browser into submitting a form on yours. Both do it with a secret token that has to come back with every form. The difference is in who writes the token into the page.

In Rails, the protection is switched on by default for new applications, and the form_with helper adds the token to every form it builds. You never see it in your template10.

In Django, the protection is also on by default, through a piece of middleware. But each form that posts data needs one tag inside it, {% csrf_token %}, written by you11.

Same protection, same default, same result. Rails puts the token there because the convention says forms need it. Django asks you to write one visible line, so anyone reading the template can see the form is protected. That is the whole philosophical difference, in one line of HTML.

The same feature, built twice

Philosophy is easier to judge in code. So here is one small, real feature built in both frameworks, the way each framework's own guides would build it: Freewheel's list of bookings, plus a form to create a booking.

To keep the comparison fair, the booking is simplified to three fields: the customer's name, the start time and some notes. In the Rails and Django chapters later in this programme, a booking belongs to a customer, a bike and a mechanic. Here it stands alone, so the code stays short enough to compare line by line. The application module is called freewheel in both versions.

Example: Freewheel's bookings in Rails 7.1

The first step creates the model and its database table:

bin/rails generate model Booking customer_name:string starts_at:datetime notes:text

This writes two files. The migration describes the table. I add null: false to the two required columns, so the database itself refuses a booking without them:

# db/migrate/20231205090000_create_bookings.rb (generated, two lines edited)
class CreateBookings < ActiveRecord::Migration[7.1]
  def change
    create_table :bookings do |t|
      t.string :customer_name, null: false
      t.datetime :starts_at, null: false
      t.text :notes

      t.timestamps # adds created_at and updated_at
    end
  end
end

The model is almost empty. It lists no columns at all, because Active Record, the Rails object relational mapper (ORM), reads them from the database:

# app/models/booking.rb
class Booking < ApplicationRecord
  validates :customer_name, :starts_at, presence: true
end

One line in the routes file creates the addresses for the list, the form and the form submission:

# config/routes.rb
Rails.application.routes.draw do
  resources :bookings, only: [:index, :new, :create]
end

The controller handles the three actions. Note that index and new never say which template to show:

# app/controllers/bookings_controller.rb
class BookingsController < ApplicationController
  def index
    @bookings = Booking.order(:starts_at)
  end

  def new
    @booking = Booking.new
  end

  def create
    @booking = Booking.new(booking_params)
    if @booking.save
      redirect_to bookings_path, notice: "Booking saved."
    else
      # 422 tells the browser the form had errors
      render :new, status: :unprocessable_entity
    end
  end

  private

  # Only these three fields may come from the form
  def booking_params
    params.require(:booking).permit(:customer_name, :starts_at, :notes)
  end
end

Then two templates, in ERB, which is HTML with Ruby inside <% %> tags:

<%# app/views/bookings/index.html.erb %>
<h1>Bookings</h1>
<p><%= notice %></p>
<ul>
  <% @bookings.each do |booking| %>
    <li><%= l booking.starts_at, format: :short %>: <%= booking.customer_name %></li>
  <% end %>
</ul>
<%= link_to "New booking", new_booking_path %>
<%# app/views/bookings/new.html.erb %>
<h1>New booking</h1>
<%= form_with model: @booking do |form| %>
  <% @booking.errors.full_messages.each do |message| %>
    <p><%= message %></p>
  <% end %>
  <div>
    <%= form.label :customer_name %>
    <%= form.text_field :customer_name %>
  </div>
  <div>
    <%= form.label :starts_at %>
    <%= form.datetime_field :starts_at %>
  </div>
  <div>
    <%= form.label :notes %>
    <%= form.text_area :notes %>
  </div>
  <%= form.submit %>
<% end %>

Run bin/rails db:migrate, start the server with bin/rails server, and /bookings shows the list. Here is everything Rails inferred without being told:

  • The class Booking reads the table bookings, because Rails pluralises the class name12.
  • The BookingsController file is found and loaded because its file name matches its class name. There is no require or import anywhere13.
  • resources :bookings maps the addresses to the actions index, new and create, and generates the helpers bookings_path and new_booking_path14.
  • The index action renders app/views/bookings/index.html.erb because nothing else was rendered, and the Rails Guides call this "convention over configuration" in action15.
  • Both pages are wrapped in app/views/layouts/application.html.erb, a layout that rails new generated.
  • form_with model: @booking knows the form should post to /bookings, because the booking is new.

Example: the same bookings in Django 5.0

Django splits a site into a project (settings and the top level address list) and apps (self contained features). Freewheel's project is freewheel, and the bookings feature becomes an app called bookings:

django-admin startproject freewheel .
python manage.py startapp bookings

The app has to be registered before Django will look at its models and templates. Two lines change in the settings. The first registers the app. The second tells Django where a shared base template lives:

# freewheel/settings.py (the two changed lines)
INSTALLED_APPS = [
    # the six django.contrib apps from startproject stay as they are
    "bookings",
]

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"],
        # the remaining options from startproject stay as they are
    },
]

The model lists every field. Django fields are required by default, so no extra option is needed for the two required ones, and blank=True marks the notes as optional16. Here is the model in full:

# bookings/models.py
from django.db import models


class Booking(models.Model):
    customer_name = models.CharField(max_length=100)
    starts_at = models.DateTimeField()
    notes = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

From the model, Django writes the migration for you:

python manage.py makemigrations bookings
python manage.py migrate

The views use Django's generic class based views, which are the shortest idiomatic way to build a list and a create form:

# bookings/views.py
from django.contrib.messages.views import SuccessMessageMixin
from django.urls import reverse_lazy
from django.views.generic import CreateView, ListView

from .models import Booking


class BookingListView(ListView):
    queryset = Booking.objects.order_by("starts_at")


class BookingCreateView(SuccessMessageMixin, CreateView):
    model = Booking
    fields = ["customer_name", "starts_at", "notes"]  # only these from the form
    success_url = reverse_lazy("bookings:index")
    success_message = "Booking saved."

The addresses are listed explicitly, each with a name, in the app's own URL file:

# bookings/urls.py
from django.urls import path

from . import views

app_name = "bookings"
urlpatterns = [
    path("", views.BookingListView.as_view(), name="index"),
    path("new/", views.BookingCreateView.as_view(), name="new"),
]

And the project's URL file includes the app's addresses under /bookings/:

# freewheel/urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
    path("bookings/", include("bookings.urls")),
]

Two templates, in the Django template language:

<!-- bookings/templates/bookings/booking_list.html -->
{% extends "base.html" %}
{% block content %}
<h1>Bookings</h1>
{% for message in messages %}<p>{{ message }}</p>{% endfor %}
<ul>
  {% for booking in booking_list %}
    <li>{{ booking.starts_at|date:"d M H:i" }}: {{ booking.customer_name }}</li>
  {% endfor %}
</ul>
<a href="{% url 'bookings:new' %}">New booking</a>
{% endblock %}
<!-- bookings/templates/bookings/booking_form.html -->
{% extends "base.html" %}
{% block content %}
<h1>New booking</h1>
<form method="post">
  {% csrf_token %}
  {{ form }}
  <button type="submit">Create booking</button>
</form>
{% endblock %}

The base.html they extend is a short HTML skeleton you write once in a templates folder at the project root. Rails generated its equivalent, the layout, when the application was created. Neither is counted below, because both are one time setup.

Run python manage.py runserver and /bookings/ shows the list. Now notice what Django inferred too:

  • The table is called bookings_booking, made from the app name and the model name17.
  • ListView chooses the template bookings/booking_list.html and puts the bookings into a variable called booking_list, both derived from the model's name18. CreateView chooses bookings/booking_form.html the same way19.
  • {{ form }} renders every field with its label and its error messages, in one tag.

And what you stated explicitly: the app's registration, every address and its name, every import, the fields on the model, the CSRF tag in the form, and the page to go to after saving.

Counting the lines: the totals are close, the distribution is not

A common claim is that Rails needs much less code than Django. For this feature it does not. I counted the lines a developer types or changes in each version, from the code above, leaving out blank lines, the comment that names each file, the shell commands, and generated code left untouched.

LayerRails 7.1Django 5.0
Data model (model and migration edits)57
URL routing19
Request handling (controller or views)2011
Templates2720
Settings and registration02
Total5349
Grouped bars of lines typed or changed for Freewheel's booking list and form, counted from the code in this article. Rails 7.1: data model 5, URL routing 1, request handling 20, templates 27, settings 0, total 53. Django 5.0: data model 7, URL routing 9, request handling 11, templates 20, settings 2, total 49. Tap or click to enlarge

Django comes out four lines shorter, mainly because its generic views and {{ form }} do in a few lines what the Rails controller and form template spell out. Rails comes out far shorter on routing and settings. Either total could be moved by a few lines with different choices. Rails has a scaffold generator that would write all of its code for you, and Django's built in admin would give a manager a working booking screen with no template at all. So the total is not the interesting number.

The interesting number is where the lines go. One way to put it is the share of lines that only connect things, routing plus settings, rather than doing anything a customer would notice. Call it the wiring share. Foundations: ratios and rates

w=LwiringLtotalw = \frac{L_{\text{wiring}}}{L_{\text{total}}}

where ww is the wiring share, LwiringL_{\text{wiring}} is the number of lines spent on URL routing, settings and registration, and LtotalL_{\text{total}} is the number of lines typed for the whole feature.

Example: working out the wiring share

For the Rails version, wiring is the one routing line and nothing in settings:

wRails=1+053=0.019 (rounded)w_{\text{Rails}} = \frac{1 + 0}{53} = 0.019 \text{ (rounded)}

where wRailsw_{\text{Rails}} is the wiring share of the Rails version, 1+01 + 0 is one routing line plus no settings lines, and 5353 is the total number of lines typed. That is 1.9%.

For the Django version, wiring is nine routing lines and two settings lines:

wDjango=9+249=0.224 (rounded)w_{\text{Django}} = \frac{9 + 2}{49} = 0.224 \text{ (rounded)}

where wDjangow_{\text{Django}} is the wiring share of the Django version, 9+29 + 2 is nine routing lines plus two settings lines, and 4949 is the total number of lines typed. That is 22.4%.

So about one line in 50 of the Rails version is wiring, against roughly one line in four or five of the Django version. Rails has not removed the wiring. It has moved it out of your files and into its conventions. Django has kept it in your files, where it costs a few lines and can be read without knowing any convention. That is the "where the knowledge lives" model from the start of this article, measured.

The search test: a way to feel the difference yourself

You do not have to take my word for any of this. There is a simple test anyone can run on a real codebase, even a manager who does not write code but can use the search box in an editor. I call it the search test.

Pick a name you see in the code. Search the whole project for where it is defined. Then ask: did the search find the answer, or did I need to know a rule?

Example: three names from Freewheel's code

Run the test on three names from the feature above.

The link helper. In Rails, new_booking_path has no definition in the project. The answer comes from a rule: resources :bookings generates it. Rails does give you a way to ask, the command bin/rails routes, which prints every route and its helper name. In Django, searching for the name "new" in the bookings URL file finds the definition directly. Point to Django.

The variable in the list template. In Django, booking_list in the template has no definition in the project. It comes from a rule: ListView names the variable after the model. In Rails, @bookings is assigned on a line in the controller that the search finds. Point to Rails.

The database table. In Rails, the table bookings appears in the migration, so the search finds it, but the link from the class Booking to that table is a pluralisation rule. In Django, the table bookings_booking appears in no file you wrote. It is also a rule, app name plus model name, visible in the generated migration only as the model name. A draw.

So the result is not "Rails hides everything, Django hides nothing". Both frameworks rely on rules. Django relies on fewer of them in the places where connections are made, and Rails on more. For a reader who knows the rules, both codebases are equally clear. For a reader who does not, Django's code explains more of itself.

Who is the source of truth for your data

The deepest practical difference between the two frameworks is easy to miss in a small example. It is the direction in which the data's shape flows.

In Rails, the database is the source of truth. You change the database with a migration, and the model learns its attributes by reading the table when the application starts12. That is why the Rails model above lists no columns. The current shape of the whole database is kept in a file called db/schema.rb, which Rails updates after each migration20.

In Django, the model class is the source of truth. You change the model in Python, and makemigrations compares it with the previous state and writes the migration for you21. That is why the Django model lists every field. The documentation's principle for models is that all the information needed to understand a model lives in the model class9.

Example: Niamh asks for a contact phone number

Freewheel wants to text customers when their bike is ready, so a booking needs a phone number.

In Rails, you start at the database:

bin/rails generate migration AddContactPhoneToBookings contact_phone:string
bin/rails db:migrate

The generator reads the migration's name, sees "Add ... To Bookings", and writes the add_column line for you. The model file does not change. booking.contact_phone simply works, because the column now exists. To see the field you open db/schema.rb, not the model.

In Django, you start at the model:

# bookings/models.py, one new line in the Booking class
    contact_phone = models.CharField(max_length=30, blank=True)
python manage.py makemigrations bookings
python manage.py migrate

Django writes a migration file containing an AddField operation for you. The model file is now the complete description of a booking, readable in one place.

Both routes take two commands and about one line. The difference shows up a year later, when someone new asks what a booking contains. In Rails the answer is in db/schema.rb, and a team often adds comments or a tool to show it in the model. In Django the answer is in the model, and the migration history is a record of how it got there.

Django infers too, and Rails lets you spell it out

It would be unfair to stop at "Rails is implicit, Django is explicit". Both frameworks sit somewhere in between, and both let you move along the line.

Django's own design philosophy asks the framework to deduce as much as possible from as little as possible9. You saw it above: inferred table names, inferred template names, an inferred context variable, and a whole form rendered by {{ form }}. Rails, for its part, never forces a convention on you. The doctrine says substitutions are possible, just not required7.

Example: overriding the defaults in both frameworks

Suppose Freewheel imports an old table from its spreadsheet days, called legacy_jobs_2019, and wants a page for it with a template name of its own choosing.

In Rails, both can be stated explicitly:

# app/models/legacy_job.rb
class LegacyJob < ApplicationRecord
  self.table_name = "legacy_jobs_2019" # use this table, not the inferred one
end

# app/controllers/legacy_jobs_controller.rb
class LegacyJobsController < ApplicationController
  def index
    @jobs = LegacyJob.all
    render "reports/old_jobs" # this template, not the inferred one
  end
end

In Django, the same two overrides:

# reports/models.py
from django.db import models


class LegacyJob(models.Model):
    description = models.TextField()

    class Meta:
        db_table = "legacy_jobs_2019"  # use this table, not the inferred one


# reports/views.py
from django.views.generic import ListView

from .models import LegacyJob


class LegacyJobListView(ListView):
    model = LegacyJob
    template_name = "reports/old_jobs.html"  # this template, not the inferred one

Each framework can be made more explicit, and each can be made more implicit. The philosophies decide the default, and the default is what you get in most of the code, because almost nobody overrides what works.

Two languages underneath

A framework inherits its personality from its language, and these two languages want different things.

Ruby, created by Yukihiro Matsumoto and first released in 1995, is built on the idea that "In Ruby, everything is an object.", even a number22. It lets you attach a block of code to any method call, and it lets you reopen and extend any class, including the built in ones. That flexibility is what makes Rails' readable mini languages possible. validates, has_many and resources look like keywords, but they are ordinary method calls that write code for you when the class loads. This is often called metaprogramming, code that writes code.

Python prefers that there be one obvious way to do something8, makes you import what you use, and rarely changes how built in types behave. Its other great strength is reach. Python is one of the most used languages of all: in the Stack Overflow Developer Survey 2023, 49.28% of all respondents said they had done extensive work in Python over the past year, against 6.23% for Ruby23. Among web frameworks the same survey gives Django 11.47% and Ruby on Rails 5.49%. Much of Python's reach comes from data science and scientific computing, which is why a Python framework sits naturally next to analysis and forecasting code.

Grouped bars for all respondents. Languages: Python 49.28%, Ruby 6.23%. Web frameworks: Django 11.47%, Ruby on Rails 5.49%. Python is used about eight times as widely as Ruby, while Django is used about twice as widely as Rails. Tap or click to enlarge

One detail in that chart is worth a second look. Python is used about eight times as widely as Ruby, but Django only about twice as widely as Rails. Most people who use Ruby professionally use it for Rails, while most Python users are doing something other than web development. A survey of volunteers is not a census, so treat these as rough proportions, not exact market shares. Hiring is covered properly in the fourth chapter of this series.

Example: tomorrow's bookings, in each language

On Friday evening, the workshop manager in Limerick wants Saturday's bookings. In Rails:

# Rails: Active Support adds `tomorrow` and `all_day` to Ruby's own classes
Booking.where(starts_at: Date.tomorrow.all_day).order(:starts_at)

In Django:

# Django: import what you use, then filter on the date part of starts_at
from datetime import timedelta

from django.utils import timezone

tomorrow = timezone.localdate() + timedelta(days=1)
Booking.objects.filter(starts_at__date=tomorrow).order_by("starts_at")

The Rails line reads almost like English, because Active Support, a part of Rails, adds methods such as Date.tomorrow and all_day to Ruby's built in date and time classes, and makes them respect the application's time zone24. The Django version is longer, and every name in it can be traced to an import or to the __date lookup that Django's query documentation describes25. The first is a pleasure to write once you know Active Support. The second is clear to anyone who knows Python. Same trade, smaller scale.

Same pattern, different names

Both frameworks follow the same classic pattern: separate the data, the logic that handles a request, and the presentation. Rails calls it model, view, controller (MVC). Django uses the same idea with different names, and its FAQ explains why: in Django a "view" describes which data you see, and a template describes how you see it, so it calls itself a model, template, view (MTV) framework, with the framework itself acting as the controller5. Both use the Active Record pattern for models, named after Martin Fowler's description, where an object wraps a database row and carries its own behaviour9.

The naming trips up everyone who moves between the two, so here is the map:

What it doesRails calls itDjango calls it
Wraps a database tableModel (Active Record)Model (the ORM)
Handles a request and picks the dataController actionView
Turns data into HTMLView (ERB template)Template
Maps addresses to codeRoutes (config/routes.rb)URLconf (urls.py)
Changes the database schemaMigration, written firstMigration, generated from the model
A self contained feature areaNo direct equivalent by default; engines existApp

Example: following one request through both

When Niamh opens the booking list, the request travels through each framework like this. A web server first hands it to the framework. In Rails that is Puma, the web server bundled with Rails26, speaking an interface called Rack. In Django it is any server that speaks the Web Server Gateway Interface (WSGI) or its asynchronous cousin (ASGI), with runserver used in development. Then the request passes through middleware, small layers that handle things like sessions and security, before the router decides which code runs.

Tap or click to enlarge
Tap or click to enlarge

The two paths have the same shape, step for step. The difference is in the small words: "found by its name" and "inferred" appear more often on the Rails side, "listed" and "named explicitly" more often on the Django side. Django's URL resolver works through the patterns in order and stops at the first match, exactly as written in your files27. Rails matches routes in the order they are declared too14, but one resources line has already expanded into several routes you did not write out.

A small Django detail shows its care for explicit addresses: if Niamh types /bookings without the final slash, Django redirects her to /bookings/ by default, so every page has exactly one address. The design philosophies page gives that reasoning9.

The same job, two philosophies

Here is the comparison in one table, for the jobs every application like Freewheel's needs on day one. Every row is documented behaviour in Rails 7.1 and Django 5.0.

The jobRails 7.1Django 5.0
Name the database tableInferred: Booking reads bookingsInferred: bookings_booking from app and model
Declare the columnsIn the migration, the model reads themIn the model, the migration is generated
Required by default at database levelNo, add null: falseYes, add null=True to allow empty
Connect addresses to coderesources generates routes and helpersEach path() written and named
Load your own codeAutoloaded by file name, no requireExplicit import in every file
Choose the templateInferred from controller and actionInferred by generic views, or named in render()
Register a featureNothing, files in app/ are picked upAdd the app to INSTALLED_APPS
Protect forms from CSRFToken added by form_with{% csrf_token %} written in each form
Logic in templatesERB, the full Ruby languageDeliberately limited template language
Back office for staffNot built inBuilt in admin
Interactive pages without a separate front endHotwire (Turbo and Stimulus) by defaultNothing bundled, your choice of library

Two rows deserve a sentence each, because they are not about philosophy but about what ships. Django includes an automatic admin interface that its documentation calls one of its most powerful parts: a back office for trusted staff, generated from your models28. For Freewheel's managers that is real value on day one, and it gets its own chapter in the Django series. Rails, since version 7, ships Hotwire as the default way to build interactive pages without a single page application, which is exactly what a live workshop board needs29. It gets its own chapter in the Rails series. Neither of these is a philosophy. They are the integrated system each framework chose to include.

Example: what the table means for Aisling and Cian

Read the table as Aisling would. Almost every Django cell describes something she can see in a Python file: an import, a list, a field, a named path. She can learn Django by reading Django code, because Python is already her language. The Rails cells are shorter, and several describe things that happen without a line of code, which she would have to learn as rules.

Now read it as Cian would. He knows neither Ruby nor Python. The Rails column promises less to write once he knows the conventions, and a default way, Hotwire, to make the workshop board update live, without the separate React application he would otherwise reach for. The Django column promises that what he reads is what runs.

Neither reading decides anything yet. It shows that the same table can favour different frameworks for different people, which is why the decision method in the sixth chapter of this series weighs the team, not just the features.

Who looks after each framework

A framework you build a business on needs stewards who will still be there in ten years. Both have them, organised differently.

Rails is steered by the Rails Core Team, which is responsible for the framework's technical evolution, manages code contributions and shepherds new releases. In November 2022 eight companies that depend on Rails, among them 37signals, GitHub and Shopify, founded The Rails Foundation with one million dollars of seed funding. The foundation works on documentation, education, marketing and events, and its announcement states that the core team remains fully responsible for the technical evolution2.

Django has been looked after since June 2008 by the Django Software Foundation, a not for profit organisation30. The project itself is run by an international team of volunteers, as the FAQ puts it5.

As I write, on 5 December 2023:

  • Rails 7.1 is the current release series, released on 5 October 2023 with a production Dockerfile for new applications, new building blocks for authentication, and more asynchronous queries31. The latest patch is 7.1.2, from 10 November 202332. Under the Rails maintenance policy, only the latest series gets bug fixes, and security fixes cover the current and the previous series, today 7.1 and 7.033.
  • Django 5.0 came out yesterday, on 4 December 2023, with database computed default values, generated fields, field groups for simpler form rendering, and facet counts in the admin filters34. It supports Python 3.10, 3.11 and 3.1235.
  • Django 4.2 is the long term support (LTS) release. With 5.0 out it has left mainstream support, but it receives security and data loss fixes until April 202634.

Example: which version Freewheel would start on

If Freewheel chose Rails, the answer is simple: Rails 7.1, on the current Ruby. There is only one current series, so there is no choice to make.

If Freewheel chose Django, there is a real choice. Django 5.0 is one day old. Django 4.2 is the conservative option, with security fixes guaranteed until April 2026. For a new project with six months until launch, I would start on 5.0: by the time Freewheel goes live, 5.0 will have had half a year of patch releases, and starting on the older release only means an upgrade sooner. The fifth chapter of this series covers what those upgrades cost over five years.

For the person paying for this

If you commission a web application and someone proposes Rails or Django, here is what you can take from this chapter without reading any code:

  • Both are serious, mature, open source choices. Neither is a risky bet. Both have been running real products since the mid 2000s and both have foundations behind them.
  • The features are closer than the sales pitch suggests. For a typical business application, both frameworks will do the job. The difference in how much code gets written is small, as the line count above shows.
  • The real difference is who can read the code. A Rails application rewards developers who know Rails. A Django project rewards developers who know Python. Ask who will maintain this in three years, and in which language they think.
  • Ask for the search test. Ask your developer to show you where one page's address, template and data come from. In either framework, a good developer can answer in a minute. If they cannot, the problem is not the framework.
  • You own the result. Whatever the framework, the code, the hosting accounts and the data should be yours. Make sure the contract says so.

If you want to see what a Rails build would look like for your own product, I describe how I work on the web application development page, and the free workshop is where we can go through your case together.

My view: the deciding difference is philosophy, not features

My view: when two frameworks are this mature, features stop being the reason to choose. Almost anything one can do, the other can do with a library or an afternoon of work. What you cannot change is the philosophy, because it is in every file the framework touches. And the philosophy decides who will be comfortable in the code.

Rails asks you to learn its conventions and pays you back with less to write and less to read. That trade is excellent for a small team that will live in one application for years, because the conventions are learned once and pay off on every page. It is a worse trade for a team that will only touch the code now and then, because every visit means remembering rules.

Django asks you to write the connections down and pays you back with code that explains itself to any Python developer. That trade is excellent when Python is the team's home, or when the web application sits next to data work in Python. It is a slightly worse trade for a team that wants the framework to make every small decision for it.

I build on Rails because, for the kind of products I build, a small team working in one integrated application, the conventions pay for themselves many times over. A senior Django developer could make an equally reasoned case for Django in a different setting, and in the next chapter I describe those settings in detail. What I would push back on is choosing either one from a feature checklist.

Example: how Freewheel should use this chapter

Niamh should not decide anything yet. She should give each developer an afternoon with the other framework's code from this article. Aisling reads the Rails version, Cian reads the Django version, and each runs the search test on five names. Then they swap. What they notice, and what slows them down, is real evidence about this team, and it will feed the decision method later in the series. That is a better use of an afternoon than reading a good few more comparison posts.

Conclusion

Django and Rails give two answers to the same question: how do you build a database backed web application quickly and well? Both were extracted from real products in the mid 2000s, both include almost everything you need, and for a typical business application their features and even their line counts are close.

The difference is where each keeps its knowledge. Rails keeps it in shared convention: less to write, but you have to know the rules. Django keeps it in your project's files: a little more to write, but the code explains itself to anyone who reads Python. The source of truth for your data flows in opposite directions, database first in Rails and model first in Django. And the languages underneath, expressive Ruby and explicit Python, carry the same split down to a single line of code.

So start with the question that actually decides it: who will read and change this code for the next five years, and which way of thinking fits them? The next chapter looks at where each framework genuinely shines.

If you are weighing Django against Rails for your own product, book the free workshop: we look at your team and your plans together, and the first two weeks of work are on me.

Sources

  1. 1.

    Ruby on Rails, rubyonrails.org homepage, archived by the Internet Archive on 2 June 2005, http://web.archive.org/web/20050602080558/http://www.rubyonrails.org:80/

  2. 2.

    The Rails Foundation, The Rails Foundation kicks off with one million dollars, rubyonrails.org, 14 November 2022, https://rubyonrails.org/2022/11/14/the-rails-foundation

  3. 3.

    Ruby on Rails, rubyonrails.org homepage ("Released Dec 13, 2005" for version 1.0), archived by the Internet Archive on 1 January 2006, http://web.archive.org/web/20060101025821/http://rubyonrails.org/

  4. 4.

    Ruby on Rails, MIT License, rails/rails repository, GitHub, https://github.com/rails/rails/blob/main/MIT-LICENSE

  5. 5.

    Django Software Foundation, FAQ: General, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/faq/general/

  6. 6.

    Django Software Foundation, contrib packages, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/contrib/

  7. 7.

    David Heinemeier Hansson, The Rails Doctrine, rubyonrails.org, 2016, https://rubyonrails.org/doctrine

  8. 8.

    Tim Peters, PEP 20, The Zen of Python, Python Software Foundation, 19 August 2004, https://peps.python.org/pep-0020/

  9. 9.

    Django Software Foundation, Design philosophies, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/misc/design-philosophies/

  10. 10.

    Ruby on Rails Guides, Securing Rails Applications, section 3.1.2 Required Security Token, Rails 7.1, https://guides.rubyonrails.org/v7.1/security.html

  11. 11.

    Django Software Foundation, How to use Django's CSRF protection, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/howto/csrf/

  12. 12.

    Ruby on Rails Guides, Active Record Basics, section 2 Convention over Configuration in Active Record, Rails 7.1, https://guides.rubyonrails.org/v7.1/active_record_basics.html

  13. 13.

    Ruby on Rails Guides, Autoloading and Reloading Constants, Rails 7.1, https://guides.rubyonrails.org/v7.1/autoloading_and_reloading_constants.html

  14. 14.

    Ruby on Rails Guides, Rails Routing from the Outside In, Rails 7.1, https://guides.rubyonrails.org/v7.1/routing.html

  15. 15.

    Ruby on Rails Guides, Layouts and Rendering in Rails, section 2.1 Rendering by Default, Rails 7.1, https://guides.rubyonrails.org/v7.1/layouts_and_rendering.html

  16. 16.

    Django Software Foundation, Model field reference, field options null and blank, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/models/fields/

  17. 17.

    Django Software Foundation, Writing your first Django app, part 2, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/intro/tutorial02/

  18. 18.

    Django Software Foundation, Built in class based generic views, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/class-based-views/generic-display/

  19. 19.

    Django Software Foundation, Generic editing views, CreateView, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/class-based-views/generic-editing/

  20. 20.

    Ruby on Rails Guides, Active Record Migrations, section on schema dumping, Rails 7.1, https://guides.rubyonrails.org/v7.1/active_record_migrations.html

  21. 21.

    Django Software Foundation, Migrations, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/migrations/

  22. 22.

    Ruby community, About Ruby, ruby-lang.org, https://www.ruby-lang.org/en/about/

  23. 23.

    Stack Overflow, 2023 Developer Survey, Technology: most popular technologies, programming languages and web frameworks, all respondents, 2023, https://survey.stackoverflow.co/2023/

  24. 24.

    Ruby on Rails Guides, Active Support Core Extensions, section 15 Extensions to Date, Rails 7.1, https://guides.rubyonrails.org/v7.1/active_support_core_extensions.html

  25. 25.

    Django Software Foundation, QuerySet API reference, the date lookup, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/models/querysets/

  26. 26.

    Ruby on Rails Guides, The Rails Command Line, section 2.1 bin/rails server, Rails 7.1, https://guides.rubyonrails.org/v7.1/command_line.html

  27. 27.

    Django Software Foundation, URL dispatcher, How Django processes a request, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/http/urls/

  28. 28.

    Django Software Foundation, The Django admin site, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/contrib/admin/

  29. 29.

    David Heinemeier Hansson, Rails 7.0: Fulfilling a vision, rubyonrails.org, 15 December 2021, https://rubyonrails.org/2021/12/15/Rails-7-fulfilling-a-vision

  30. 30.

    Django Software Foundation, Announcing the Django Software Foundation, djangoproject.com weblog, 17 June 2008, https://www.djangoproject.com/weblog/2008/jun/17/foundation/

  31. 31.

    Rafael França, Rails 7.1: Dockerfiles, BYO Authentication, More Async Queries, and more, rubyonrails.org, 5 October 2023, https://rubyonrails.org/2023/10/5/Rails-7-1-0-has-been-released

  32. 32.

    Rafael França, Rails 7.1.2 has been released, rubyonrails.org, 10 November 2023, https://rubyonrails.org/2023/11/10/Rails-7-1-2-has-been-released

  33. 33.

    Ruby on Rails Guides, Maintenance Policy for Ruby on Rails, Rails 7.1, https://guides.rubyonrails.org/v7.1/maintenance_policy.html

  34. 34.

    Natalia Bidart, Django 5.0 released, djangoproject.com weblog, 4 December 2023, https://www.djangoproject.com/weblog/2023/dec/04/django-50-released/

  35. 35.

    Django Software Foundation, FAQ: Installation, which Python version can I use with Django, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/faq/install/

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter