Django vs Flask
last modified November 22, 2026 Python 3.15
Django and Flask are the two best-known Python web frameworks, and they follow opposite philosophies. Flask is a microframework: a small core built on the Werkzeug WSGI toolkit and the Jinja template engine, with everything else, such as a database layer or form validation, added by extensions or written by hand. Django comes with batteries included: an ORM with migrations, forms, authentication, an admin site, and security middleware are part of the framework.
In this article we build the same small application with both frameworks and compare them step by step. The application stores bookmarks: a page lists them and has a form for adding new ones, the input is validated, and a JSON API returns the bookmarks. The examples use Flask 3.1 with Flask-SQLAlchemy 3.1, Django 6.1, and Python 3.15. The frameworks are covered in more depth in Python Flask and Django introduction.
The Flask project
Both projects are managed with uv. The Flask project needs Flask and the Flask-SQLAlchemy extension, which connects Flask with the SQLAlchemy toolkit.
$ mkdir marks-flask $ cd marks-flask $ uv init --bare $ uv add flask flask-sqlalchemy
There is no project generator; a Flask application can be a single Python file. The uv pip list
command shows what was installed. Besides Flask and SQLAlchemy, there are Werkzeug (the WSGI layer), Jinja and
MarkupSafe (templates), Click (the command line), itsdangerous (signed cookies), and blinker (signals).
$ uv pip list Package Version ----------------- ------- blinker 1.9.0 click 8.5.1 flask 3.1.3 flask-sqlalchemy 3.1.1 itsdangerous 2.2.0 jinja2 3.1.6 markupsafe 3.0.4 sqlalchemy 2.1.9 typing-extensions 4.16.0 werkzeug 3.1.9
The Django project
The Django project is generated by django-admin startproject with the configuration package
config; the application code goes into the app bookmarks.
$ mkdir marks-django $ cd marks-django $ uv init --bare $ uv add django $ uv run django-admin startproject config . $ uv run python manage.py startapp bookmarks
The app is added to INSTALLED_APPS in config/settings.py; the other entries are
generated by startproject.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bookmarks',
]
Django has only two dependencies: asgiref, which connects synchronous and asynchronous code, and sqlparse,
which formats SQL. Everything else is in the django package itself.
$ uv pip list Package Version -------- ------- asgiref 3.13.0 django 6.1.3 sqlparse 0.6.1
A first page in Flask
The first version of each application returns a line of text from the home page. In Flask, the application object and the routes live in one module.
from flask import Flask
app = Flask(__name__)
@app.get('/')
def index():
return 'Bookmarks will be here.\n'
The Flask object is the application. The @app.get('/') decorator registers the
function for GET requests to /; a string returned from a view becomes an HTML response. We start
the development server with the flask command; the --app option names the module.
$ uv run flask --app app run
In a second terminal, we request the page with curl. The server listens on port 5000. It does not
reload changed code unless it is started with --debug, so we restart it after each change.
$ curl -si localhost:5000/ HTTP/1.1 200 OK Server: Werkzeug/3.1.9 Python/3.15.2 Date: Sun, 22 Nov 2026 17:26:44 GMT Content-Type: text/html; charset=utf-8 Content-Length: 24 Connection: close Bookmarks will be here.
A first page in Django
In Django, the view and the route are kept apart. The view is a function in the app's views.py
module.
from django.http import HttpResponse
def index(request):
return HttpResponse('Bookmarks will be here.\n')
A Django view receives an HttpRequest object as an explicit argument, while Flask provides the
request through the global request proxy. The view must return an HttpResponse. The
route is defined in the project's URLconf.
from django.contrib import admin
from django.urls import path
from bookmarks import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
]
The urlpatterns list maps paths to views; the admin route is generated by
startproject. The development server is started through manage.py.
$ uv run python manage.py runserver
Django's server listens on port 8000 and reloads itself when a file changes. The body is the same, but the
response carries four security headers added by Django's middleware: protection against clickjacking
(X-Frame-Options), against MIME type sniffing, and two policies limiting what other sites can
see. Flask sends none of them by default.
$ curl -si localhost:8000/ HTTP/1.1 200 OK Date: Sun, 22 Nov 2026 17:26:44 GMT Server: WSGIServer CPython/3.15.2 Content-Type: text/html; charset=utf-8 X-Frame-Options: DENY Content-Length: 24 X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin Bookmarks will be here.
A model in Flask
A bookmark has a title, a URL, and the time it was created. In Flask, we use SQLAlchemy through the Flask-SQLAlchemy extension.
from datetime import datetime, timezone
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///bookmarks.db'
db = SQLAlchemy(app, model_class=Base)
class Bookmark(db.Model):
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(db.String(100))
url: Mapped[str] = mapped_column(db.String(200))
created: Mapped[datetime] = mapped_column(
default=lambda: datetime.now(timezone.utc))
@app.cli.command('init-db')
def init_db():
db.create_all()
print('Created the tables.')
@app.get('/')
def index():
return 'Bookmarks will be here.\n'
The SQLAlchemy object is created with a declarative base class, as SQLAlchemy 2 recommends, and
the database URI is set in the application's configuration; a relative SQLite path is placed in the
instance folder. The columns are declared with type annotations and mapped_column().
The default creation time is computed by a function in Python. The @app.cli.command decorator
adds the init-db command to the flask tool; it creates the tables with
db.create_all().
We run the command and print the schema with the sqlite3 tool. The create_all()
method creates missing tables but never changes existing ones: when we tried adding a column to the model and
running init-db again, the command succeeded and the table stayed as it was. Changing the schema
of a live database needs the Flask-Migrate extension, which wraps the Alembic migration tool.
$ uv run flask --app app init-db Created the tables. $ sqlite3 instance/bookmarks.db .schema CREATE TABLE bookmark ( id INTEGER NOT NULL, title VARCHAR(100) NOT NULL, url VARCHAR(200) NOT NULL, created DATETIME NOT NULL, PRIMARY KEY (id) );
A model in Django
In Django, models are classes in the app's models.py module.
from django.db import models
class Bookmark(models.Model):
title = models.CharField(max_length=100)
url = models.URLField()
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created']
def __str__(self):
return self.title
The URLField is a varchar column with a maximum length of 200, which is also
validated as a URL in forms. The auto_now_add option fills in the creation time, and the
Meta.ordering option sorts the bookmarks from the newest. Django names the table after the app
and the model.
Migrations are part of Django. The makemigrations command compares the models with the existing
migration files and writes a new one; migrate applies it. Later changes to the model produce new
migrations in the same way. The first migrate also creates the tables of the built-in apps:
users, permissions, sessions, and the admin log.
$ uv run python manage.py makemigrations bookmarks
Migrations for 'bookmarks':
bookmarks/migrations/0001_initial.py
+ Create model Bookmark
$ uv run python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, bookmarks, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying bookmarks.0001_initial... OK
Applying sessions.0001_initial... OK
$ sqlite3 db.sqlite3 ".schema bookmarks_bookmark"
CREATE TABLE IF NOT EXISTS "bookmarks_bookmark" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(100) NOT NULL, "url" varchar(200) NOT NULL, "created" datetime NOT NULL);
Templates in Flask
The home page now renders a template with the list of bookmarks. We add a helper function that loads them and change the view.
from datetime import datetime, timezone
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///bookmarks.db'
db = SQLAlchemy(app, model_class=Base)
class Bookmark(db.Model):
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(db.String(100))
url: Mapped[str] = mapped_column(db.String(200))
created: Mapped[datetime] = mapped_column(
default=lambda: datetime.now(timezone.utc))
@app.cli.command('init-db')
def init_db():
db.create_all()
print('Created the tables.')
def all_bookmarks():
query = db.select(Bookmark).order_by(Bookmark.created.desc())
return db.session.execute(query).scalars().all()
@app.get('/')
def index():
return render_template('index.html', bookmarks=all_bookmarks())
The query is built with db.select() and executed in the session; scalars() returns
the model objects instead of rows. The render_template() function looks for templates in the
templates directory next to the application module.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bookmarks</title>
</head>
<body>
<h1>Bookmarks</h1>
<ul>
{% for bookmark in bookmarks %}
<li><a href="{{ bookmark.url }}">{{ bookmark.title }}</a>
{{ bookmark.created.strftime('%Y-%m-%d') }}</li>
{% else %}
<li>No bookmarks yet.</li>
{% endfor %}
</ul>
<form method="post" action="{{ url_for('index') }}">
{% if error %}<p>{{ error }}</p>{% endif %}
<input name="title" value="{{ title }}" placeholder="Title">
<input name="url" value="{{ url }}" placeholder="https://...">
<button>Add</button>
</form>
</body>
</html>
Jinja templates can call methods with arguments, so the date is formatted with strftime(). The
else branch of the for loop runs for an empty list. The url_for()
function builds the URL from the name of the view function. The form already contains the error,
title, and url variables, which we use in the next step; undefined variables are
rendered as empty strings.
$ curl -s localhost:5000/ | grep -E '<(li|input)' <li>No bookmarks yet.</li> <input name="title" value="" placeholder="Title"> <input name="url" value="" placeholder="https://...">
Templates in Django
In Django, we do not write the form fields by hand. A ModelForm builds them from the model.
from django import forms
from .models import Bookmark
class BookmarkForm(forms.ModelForm):
class Meta:
model = Bookmark
fields = ['title', 'url']
The form takes the field types, maximum lengths, and validation from the title and
url model fields. The view passes the bookmarks and an empty form to the template.
from django.shortcuts import render
from .forms import BookmarkForm
from .models import Bookmark
def index(request):
context = {'bookmarks': Bookmark.objects.all(), 'form': BookmarkForm()}
return render(request, 'bookmarks/index.html', context)
The Bookmark.objects.all() QuerySet is sorted by the model's default ordering. The template lives
in the app's templates directory, inside a subdirectory named after the app, so that templates of
different apps do not collide.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bookmarks</title>
</head>
<body>
<h1>Bookmarks</h1>
<ul>
{% for bookmark in bookmarks %}
<li><a href="{{ bookmark.url }}">{{ bookmark.title }}</a>
{{ bookmark.created|date:'Y-m-d' }}</li>
{% empty %}
<li>No bookmarks yet.</li>
{% endfor %}
</ul>
<form method="post" action="{% url 'index' %}">
{% csrf_token %}
{{ form }}
<button>Add</button>
</form>
</body>
</html>
The Django template language does not allow calling methods with arguments; the date is formatted with the
date filter. The empty case is handled by {% empty %}, and {% url %}
takes the route name. The {% csrf_token %} tag inserts a hidden field with a token, and {{
form }} renders the labels and inputs with the maxlength, required, and
type="url" attributes taken from the model.
$ curl -s localhost:8000/ | grep -E '<(li|label|input)'
<li>No bookmarks yet.</li>
<input type="hidden" name="csrfmiddlewaretoken" value="iyw0bpqc967I1Jp4TszStd6wtLl2ZCSMNX4Xx72dBNM8921QBEF7mEqoJ5KLoCAP">
<label for="id_title">Title:</label>
<input type="text" name="title" maxlength="100" required id="id_title">
<label for="id_url">Url:</label>
<input type="url" name="url" maxlength="200" required id="id_url">
Forms in Flask
Flask has no form library; the Flask-WTF extension is a popular choice, but we validate the input by hand to see what is involved. A separate view handles POST requests to the home page.
from datetime import datetime, timezone
from urllib.parse import urlparse
from flask import Flask, redirect, render_template, request, url_for
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///bookmarks.db'
db = SQLAlchemy(app, model_class=Base)
class Bookmark(db.Model):
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(db.String(100))
url: Mapped[str] = mapped_column(db.String(200))
created: Mapped[datetime] = mapped_column(
default=lambda: datetime.now(timezone.utc))
@app.cli.command('init-db')
def init_db():
db.create_all()
print('Created the tables.')
def all_bookmarks():
query = db.select(Bookmark).order_by(Bookmark.created.desc())
return db.session.execute(query).scalars().all()
@app.get('/')
def index():
return render_template('index.html', bookmarks=all_bookmarks())
@app.post('/')
def add_bookmark():
title = request.form.get('title', '').strip()
url = request.form.get('url', '').strip()
parts = urlparse(url)
error = None
if not title or len(title) > 100:
error = 'Enter a title of at most 100 characters.'
elif parts.scheme not in ('http', 'https') or not parts.netloc:
error = 'Enter a valid http or https URL.'
if error:
return render_template('index.html', bookmarks=all_bookmarks(),
error=error, title=title, url=url), 400
db.session.add(Bookmark(title=title, url=url))
db.session.commit()
return redirect(url_for('index'))
The request.form object holds the submitted fields. The title must not be empty and must fit into
the column. The URL is parsed with urlparse() and must have an http or
https scheme and a host name. When the input is invalid, the page is rendered again with the
error message, the entered values, and the status code 400. Otherwise, the bookmark is saved and the browser
is redirected to the list, so that a reload does not submit the form twice.
We send the form data with curl. The valid bookmark is saved, the URL without a scheme is
rejected, and Jinja escapes the HTML in the title. The form is accepted from any client without a token: Flask
has no protection against cross-site request forgery, in which another site makes the user's browser submit a
form. That protection must come from an extension such as Flask-WTF.
$ curl -si -d 'title=Python docs' -d 'url=https://docs.python.org/3/' localhost:5000/ | head -5
HTTP/1.1 302 FOUND
Server: Werkzeug/3.1.9 Python/3.15.2
Date: Sun, 22 Nov 2026 17:26:48 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 189
$ curl -s -o /dev/null -w '%{http_code}\n' -d 'title=Example' -d 'url=example.com' localhost:5000/
400
$ curl -s -d 'title=Example' -d 'url=example.com' localhost:5000/ | grep '<p>'
<p>Enter a valid http or https URL.</p>
$ curl -s -d 'title=<b>Flask</b>' -d 'url=https://flask.palletsprojects.com/' localhost:5000/ -o /dev/null
$ curl -s localhost:5000/ | grep -A1 '<li>'
<li><a href="https://flask.palletsprojects.com/"><b>Flask</b></a>
2026-11-22</li>
--
<li><a href="https://docs.python.org/3/">Python docs</a>
2026-11-22</li>
Forms in Django
The Django view handles both GET and POST requests and lets the form do the validation.
from django.shortcuts import redirect, render
from .forms import BookmarkForm
from .models import Bookmark
def index(request):
status = 200
if request.method == 'POST':
form = BookmarkForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
status = 400
else:
form = BookmarkForm()
context = {'bookmarks': Bookmark.objects.all(), 'form': form}
return render(request, 'bookmarks/index.html', context, status=status)
The form is bound to the POST data. The is_valid() method runs the validation of all fields, and
save() creates the model instance, because a ModelForm knows its model. An invalid
form is rendered again with its errors and the entered values; the status code 400 is our choice, Django would
send 200 by default.
The first request without a token is refused with 403 by the CSRF middleware, which is enabled by default. A
browser gets the token in the page and in a cookie; with curl, we load the page, keep the cookie
in a file, and send the token from the page with the form. Then the bookmark is saved. The
URLField form field adds the https:// scheme to example.com instead of
rejecting it; a value that is not a URL at all gets an error message.
$ curl -s -o /dev/null -w '%{http_code}\n' -d 'title=Python docs' -d 'url=https://docs.python.org/3/' localhost:8000/
403
$ curl -s -c cookies.txt -o page.html localhost:8000/
$ TOKEN=$(grep -o 'csrfmiddlewaretoken" value="[^"]*' page.html | cut -d'"' -f3)
$ curl -si -b cookies.txt -d csrfmiddlewaretoken=$TOKEN -d 'title=Django docs' -d 'url=https://docs.djangoproject.com/' localhost:8000/ | grep -E '^(HTTP|Location)'
HTTP/1.1 302 Found
Location: /
$ curl -s -b cookies.txt -d csrfmiddlewaretoken=$TOKEN -d 'title=Example' -d 'url=example.com' localhost:8000/ -o /dev/null -w '%{http_code}\n'
302
$ curl -s -b cookies.txt -d csrfmiddlewaretoken=$TOKEN -d 'title=Example' -d 'url=not a url' localhost:8000/ | grep errorlist
<ul class="errorlist" id="id_url_error"><li>Enter a valid URL.</li></ul>
$ curl -s localhost:8000/ | grep -A1 '<li>'
<li><a href="https://example.com">Example</a>
2026-11-22</li>
--
<li><a href="https://docs.djangoproject.com/">Django docs</a>
2026-11-22</li>
JSON in Flask
The API returns the bookmarks as JSON. We add a to_dict() method to the model and two views.
from datetime import datetime, timezone
from urllib.parse import urlparse
from flask import Flask, redirect, render_template, request, url_for
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///bookmarks.db'
db = SQLAlchemy(app, model_class=Base)
class Bookmark(db.Model):
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(db.String(100))
url: Mapped[str] = mapped_column(db.String(200))
created: Mapped[datetime] = mapped_column(
default=lambda: datetime.now(timezone.utc))
def to_dict(self):
return {'id': self.id, 'title': self.title, 'url': self.url,
'created': self.created.isoformat()}
@app.cli.command('init-db')
def init_db():
db.create_all()
print('Created the tables.')
def all_bookmarks():
query = db.select(Bookmark).order_by(Bookmark.created.desc())
return db.session.execute(query).scalars().all()
@app.get('/')
def index():
return render_template('index.html', bookmarks=all_bookmarks())
@app.post('/')
def add_bookmark():
title = request.form.get('title', '').strip()
url = request.form.get('url', '').strip()
parts = urlparse(url)
error = None
if not title or len(title) > 100:
error = 'Enter a title of at most 100 characters.'
elif parts.scheme not in ('http', 'https') or not parts.netloc:
error = 'Enter a valid http or https URL.'
if error:
return render_template('index.html', bookmarks=all_bookmarks(),
error=error, title=title, url=url), 400
db.session.add(Bookmark(title=title, url=url))
db.session.commit()
return redirect(url_for('index'))
@app.get('/api/bookmarks')
def api_list():
return [bookmark.to_dict() for bookmark in all_bookmarks()]
@app.get('/api/bookmarks/<int:bookmark_id>')
def api_detail(bookmark_id):
return db.get_or_404(Bookmark, bookmark_id).to_dict()
A Flask view can return a list or a dictionary; Flask converts it to a JSON response. The
<int:bookmark_id> converter matches whole numbers and passes them to the view, and
db.get_or_404() returns the object or aborts with the status code 404.
Flask sorts the keys and writes compact JSON. The creation time has no time zone: SQLite has no date type, and
SQLAlchemy returns naive datetimes from a plain DateTime column.
$ curl -s localhost:5000/api/bookmarks
[{"created":"2026-11-22T17:26:48.598261","id":2,"title":"<b>Flask</b>","url":"https://flask.palletsprojects.com/"},{"created":"2026-11-22T17:26:48.550554","id":1,"title":"Python docs","url":"https://docs.python.org/3/"}]
$ curl -si localhost:5000/api/bookmarks/1 | grep -E '^(HTTP|Content-Type)'
HTTP/1.1 200 OK
Content-Type: application/json
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:5000/api/bookmarks/9
404
JSON in Django
The same method is added to the Django model.
from django.db import models
class Bookmark(models.Model):
title = models.CharField(max_length=100)
url = models.URLField()
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created']
def __str__(self):
return self.title
def to_dict(self):
return {'id': self.id, 'title': self.title, 'url': self.url,
'created': self.created.isoformat()}
The views return JsonResponse objects. A list must be allowed explicitly with
safe=False, a guard against an old JSON vulnerability in browsers.
from django.http import JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from .forms import BookmarkForm
from .models import Bookmark
def index(request):
status = 200
if request.method == 'POST':
form = BookmarkForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
status = 400
else:
form = BookmarkForm()
context = {'bookmarks': Bookmark.objects.all(), 'form': form}
return render(request, 'bookmarks/index.html', context, status=status)
def api_list(request):
data = [bookmark.to_dict() for bookmark in Bookmark.objects.all()]
return JsonResponse(data, safe=False)
def api_detail(request, pk):
bookmark = get_object_or_404(Bookmark, pk=pk)
return JsonResponse(bookmark.to_dict())
The get_object_or_404() shortcut raises Http404 when there is no such row. The two
API routes are added to the URLconf.
from django.contrib import admin
from django.urls import path
from bookmarks import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
path('api/bookmarks/', views.api_list),
path('api/bookmarks/<int:pk>/', views.api_detail),
]
The <int:pk> converter works like Flask's. Django's routes conventionally end with a slash.
Django keeps the key order and adds the time zone offset, because USE_TZ is on and times are
stored in UTC. A request without the trailing slash is redirected with 301 by the APPEND_SLASH
setting.
$ curl -s localhost:8000/api/bookmarks/
[{"id": 2, "title": "Example", "url": "https://example.com", "created": "2026-11-22T17:26:49.333470+00:00"}, {"id": 1, "title": "Django docs", "url": "https://docs.djangoproject.com/", "created": "2026-11-22T17:26:49.313416+00:00"}]
$ curl -si localhost:8000/api/bookmarks/1/ | grep -E '^(HTTP|Content-Type)'
HTTP/1.1 200 OK
Content-Type: application/json
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/api/bookmarks/9/
404
$ curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' localhost:8000/api/bookmarks
301 http://localhost:8000/api/bookmarks/
The admin site
Django generates an administration interface for registered models. Nine lines give us a page for listing, searching, adding, editing, and deleting bookmarks.
from django.contrib import admin
from .models import Bookmark
@admin.register(Bookmark)
class BookmarkAdmin(admin.ModelAdmin):
list_display = ['title', 'url', 'created']
search_fields = ['title', 'url']
The list_display option selects the columns of the list and search_fields adds a
search box. An administrator account is created with the createsuperuser command, here without
prompts; the password comes from an environment variable. The admin then logs in at /admin/, and
anonymous requests are redirected to the login page. Flask has nothing comparable built in; the Flask-Admin
extension fills the gap. The login, sessions, and permissions behind the admin also come from Django; in
Flask, they need extensions such as Flask-Login.
$ DJANGO_SUPERUSER_PASSWORD=s3cret-pass uv run python manage.py createsuperuser --noinput --username admin --email admin@example.com
Superuser created successfully.
$ curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' localhost:8000/admin/
302 http://localhost:8000/admin/login/?next=/admin/
Counting the code
Both applications do the same work, except that the Django one also has an admin site and CSRF protection. We
count the lines that we wrote; the files generated by startproject and startapp, the
settings, and the migration are not included.
The totals are almost the same. Flask needs fewer files, while the Django code is spread over modules with
fixed roles. In Flask, about a quarter of the module is the hand-written validation; in Django, the validation
comes with the model. The du command shows the size of the installed packages: Flask with
SQLAlchemy takes 31 MB, Django 48 MB. The first listing is from the Flask project directory, the second from
the Django one.
$ wc -l app.py templates/index.html 74 app.py 24 templates/index.html 98 total $ du -sh .venv/lib/python3.15/site-packages 31M .venv/lib/python3.15/site-packages
$ wc -l config/urls.py bookmarks/{models,forms,views,admin}.py bookmarks/templates/bookmarks/index.html
11 config/urls.py
17 bookmarks/models.py
9 bookmarks/forms.py
30 bookmarks/views.py
9 bookmarks/admin.py
23 bookmarks/templates/bookmarks/index.html
99 total
$ du -sh .venv/lib/python3.15/site-packages
48M .venv/lib/python3.15/site-packages
Comparison
The table sums up how the two frameworks handled each part of the application.
| Topic | Flask | Django |
|---|---|---|
| Project layout | One module, structure is up to us | startproject, apps with fixed modules |
| Routing | Decorators on view functions | URLconf lists in urls.py |
| Request object | Global request proxy | Argument of every view |
| Database | Flask-SQLAlchemy extension | Built-in ORM |
| Schema changes | create_all(); Flask-Migrate for migrations | Built-in migrations |
| Templates | Jinja; method calls allowed | Django template language; filters |
| Forms | By hand or Flask-WTF | Form and ModelForm |
| CSRF protection | Flask-WTF | On by default |
| Security headers | None by default | Added by middleware |
| Admin interface | Flask-Admin extension | django.contrib.admin |
| Users and login | Flask-Login extension | django.contrib.auth |
| Dependencies | Flask plus chosen extensions | Django, asgiref, sqlparse |
In both frameworks, each part can be replaced: Flask applications choose their extensions, and Django projects can use Jinja templates or another ORM, although many of Django's built-in apps depend on its own ORM.
Which one to choose
Flask suits small services, APIs, and prototypes, and projects that want to pick each component themselves; a Flask application stays small and explicit, and every part can be understood quickly. As the application grows, we make the decisions that Django has already made: the project structure, the extensions, and how they work together.
Django suits database-driven sites with users, forms, and an administration interface, and teams that benefit from a common structure. Its built-in parts are designed to work together and are secure by default, as the CSRF check and the security headers showed. The price is more files and concepts to learn at the start. For JSON APIs, Django is usually combined with the Django REST framework.
Source
Flask-SQLAlchemy documentation
In this article we have built the same bookmarks application with Flask and with Django and compared the projects, routing, models and migrations, templates, forms with CSRF protection, JSON responses, and the admin site. Related articles are Python Flask, Django introduction, Django ModelForm, Django migrations, and Django admin site.
Author
List all Django tutorials.