Django Project With Only 1 File, And 13 Lines Of Code

Django Project With Only 1 File, And 13 Lines Of Code

/ #Django


You might wonder how small you can make a django project. Keep reading to see how you can make a Django project with only 1 file and 13 lines of code, and this include line breaks

Typically when you create a new django project, you get files like settings.py, urls.py, wsgi.py and similar. These files help you build projects with best practices and similar.

But for testing purposes, I want to create the most minimal Django project possible.

I have already installed django, so the first task now is to create a new file called small.py. We need to set three constants and add an empty urlpatterns list:

DEBUG = True
SECRET_KEY = 'this.must.be.secure'
ROOT_URLCONF = __name__

urlpatterns = []

Let's try to run this project now:

django-admin runserver --pythonpath=. --settings=small

So the "pythonpath" variable here points to the Python instance in your computer or environment. The "settings" variable points to the "small.py" file we just created.

Okay, at least we now see the default django welcome page. Let's make it possible to add a view, and render some html.

from django.http import HttpResponse
from django.urls import path

DEBUG = True
SECRET_KEY = 'thismustbesecure'
ROOT_URLCONF = __name__

def index(request):
    return HttpResponse('<p>A really small Django project</p>')

urlpatterns = [
    path('', index),
]

If we run it again now, we will see the paragraph we added. So there you have it, a django project with only 1 file and 13 lines of code.

We can also make it possible to use the "python small.py run server" command by doing some changes.

import sys

from django.conf import settings
from django.core.management import execute_from_command_line
from django.http import HttpResponse
from django.urls import path

settings.configure(
    DEBUG=True,
    SECRET_KEY='thismustbesecure',
    ROOT_URLCONF=__name__,
)

def index(request):
    return HttpResponse('<p>A 22 lines Django project</p>')

urlpatterns = [
    path('', index),
]

if __name__ == '__main__':
    execute_from_command_line(sys.argv)

Now, you should be able to run the project by running this command:

python small.py runserver

Even though this project would never be used in real life, it's interesting to test out. If you want to learn more about django, check out my premium courses or my free tutorials on YouTube.

Video

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.