Skip to content

Django Getting Started

  • Create virtualenv and source it
  • Install packages
    Django==3.1.3
    djangorestframework==3.12.2
    psycopg2-binary==2.8.6
    
  • Start project and move to the newly created directory

    $ django-admin startproject my-project
    $ cd my-project
    

  • Update DB Information - in this example we are adding postgres database

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'OPTIONS': {
                'options': '-c search_path=public'
            },
            'NAME': 'my_db_name',
            'USER': 'my_db_user',
            'PASSWORD': 'my_db_pass',
            'HOST': 'my_db_server_ip',
            'PORT': 'my_db_server_port',
        }
    }
    

  • Start App for my-app
    python manage.py startapp my-app
    
  • Add this app in project settings.py -> my-project/settings.py

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'my-app',
    ]
    

  • Create my-app models my-app/models.py

    • Allows us to create and define tables in database.
  • Make Migrations

    • Make migrations
      python manage.py makemigrations
      
    • Migrate

      python manage.py migrate
      

      Note

      DO NOT DELETE OLD MIGRATION FILES AND KEEP THEM IN SOURCE CODE

  • Create Seriliaser my-app/serializers.py

    • Allows us to access and update items in database using models.
  • Update views my-app/views.py.

    • Allows us to render response associated with URLs.
      • Custome API response
      • Render HTTPResponse
  • Update url's my-app/urls.py

    • Allows us to define URL paths
  • Update project url my-project/urls.py to allow URLs defined for our app.

    urlpatterns = [
        path('', include('my-app.urls'))
    ]
    

Back to top