> ~ biozz / Blog

Django Single File

A modern guide to making things unnecessary

Ivan Elfimov, 2023-03-03, 2m (310 words)

Sometimes it is good to brake things to better understand what they do. And more importantly why they do.

There have been a couple of attempts in the past to “break” Django in a way that it works like Flask, i.e. as little code as possible, using only one file.

Even though they all mention Django models, they don’t include them into their examples. That’s what I am going to present to you.

Here is a proof of concept of single file Django, using all the goodies, like models and admin.

Well, it is not exactly single file, because it is going to generate migrations, but I think that’s okay.

import html
import os
import sys

from django.conf import settings
from django.core.wsgi import get_wsgi_application
from django.http import HttpResponse
from django.urls import path
from django.db import models
from django.contrib import admin
from django.conf.urls.static import static


settings.configure(
    DEBUG=(os.environ.get("DEBUG", "") == "1"),
    INSTALLED_APPS=[
        "__main__",
        "django.contrib.admin",
        "django.contrib.auth",
        "django.contrib.contenttypes",
        "django.contrib.sessions",
        "django.contrib.messages",
        'django.contrib.staticfiles',
    ],
    TEMPLATES=[
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "DIRS": [],
            "APP_DIRS": True,
            "OPTIONS": {
                "context_processors": [
                    "django.template.context_processors.debug",
                    "django.template.context_processors.request",
                    "django.contrib.auth.context_processors.auth",
                    "django.contrib.messages.context_processors.messages",
                ],
            },
        },
    ],
    MIDDLEWARE=[
        "django.middleware.security.SecurityMiddleware",
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.common.CommonMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django.middleware.clickjacking.XFrameOptionsMiddleware",
    ],
    DEFAULT_AUTO_FIELD='django.db.models.BigAutoField',
    DATABASES={
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': 'db.sqlite3',
        }
    },
    ALLOWED_HOSTS=["*"],
    ROOT_URLCONF=__name__,
    STATIC_URL='static/',
    STATIC_ROOT='static',
    SECRET_KEY=os.environ.get("SECRET_KEY", "local"),
)

app = get_wsgi_application()


def index(request):
    name = request.GET.get("name", "World")
    return HttpResponse(f"Hello, {html.escape(name)}!")


urlpatterns = [
    path("admin/", admin.site.urls),
    path("", index),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


class Analysis(models.Model):
    name = models.CharField(max_length=150)


class Entry(models.Model):
    analysis = models.ForeignKey(Analysis, on_delete=models.PROTECT)
    result = models.CharField(max_length=255)
    normal = models.CharField(max_length=255)
    comment = models.TextField(null=True)


@admin.register(Analysis)
class AnalysisAdmin(admin.ModelAdmin):
    pass


@admin.register(Entry)
class EntryAdmin(admin.ModelAdmin):
    pass


if __name__ == "__main__":
    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

For now I am stuck with this error: Reverse for 'app_list' with keyword arguments '{'app_label': '__main__'}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth)/$'].

And at this point it seems too complicated for a working concept, so I am going to leave it as it is for now.