A minimal Django application

django python

2024-09-18


I wanted to put together a single-file Django application, which could still do 'useful' work; that is, define models, operate on them, and setup URL routing.

I ended up with two files. The first, application.py:

import os
from django.db import models
from django.http import HttpResponse
from django.urls import path, re_path
from django.core.wsgi import get_wsgi_application
from django.contrib.auth.decorators import login_required
from django.contrib.auth import views as auth_views

# Assuming settings.py is in the same directory
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')

# Define the Django model
class MyModel(models.Model):
    name = models.CharField(max_length=100)

# Define the view functions
def index(request):
    return HttpResponse("Hello, world!")

@login_required
def authenticated_index(request):
    return HttpResponse("Hello, authenticated user!")

# Define the URL patterns
urlpatterns = [
    path('', index, name='index'),
    path('authenticated/', authenticated_index, name='authenticated_index'),
    path('login/', auth_views.LoginView.as_view(), name='login'),
]

# Create the WSGI application
application = get_wsgi_application()

And the second, settings.py:

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

SECRET_KEY = 'your_secret_key'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes', 
]

ROOT_URLCONF = 'application'  # Point to the application file.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        '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',
            ],
        },
    },
]

ALLOWED_HOSTS = []  # Update for deployment 

Edit 2024-09-26: I just found out about nanodjango, which is a much more polished experience. Check it out.