Django Single File Hello World Example


Example

This example shows you a minimal way to create a Hello World page in Django. This will help you realize that the django-admin startproject example command basically creates a bunch of folders and files and that you don't necessarily need that structure to run your project.

  1. Create a file called file.py.

  2. Copy and paste the following code in that file.

     import sys
     
     from django.conf import settings
     
     settings.configure(
         DEBUG=True,
         SECRET_KEY='thisisthesecretkey',
         ROOT_URLCONF=__name__,
         MIDDLEWARE_CLASSES=(
             'django.middleware.common.CommonMiddleware',
             'django.middleware.csrf.CsrfViewMiddleware',
             'django.middleware.clickjacking.XFrameOptionsMiddleware',
         ),
     )
     
     from django.conf.urls import url
     from django.http import HttpResponse
     
     # Your code goes below this line.
    
     def index(request):
         return HttpResponse('Hello, World!')
    
     urlpatterns = [
         url(r'^$', index),
     ]
    
     # Your code goes above this line
     
     if __name__ == "__main__":
         from django.core.management import execute_from_command_line
     
         execute_from_command_line(sys.argv)
    
  3. Go to the terminal and run the file with this command python file.py runserver.

  4. Open your browser and go to 127.0.0.1:8000.