mkumaran.net

Getting started Django

April 10, 2021

Install

Ensure that python is already installed. CheckPythonVersion

install virtual environment

pip install virtualenvwrapper-win

InstallVirtualEnvWarpper

Create virtual environment

mkvirtualenv djangoprj

CreatingVirtualEnv

Install Django

ensure that you are inside the virtual environment

pip install django

InstallDjango

Run below command to check django is installed

django-admin --version

EnsureDjangoInstalled

Create project

django-admin startproject djsample

CreateDjangoProject

NewFolderCreatedForProject

Run project

cd djsample

GoToInsideTheProjectToRun

py manage.py runserver

RunDjangoProjectsServer Do not close the above window.

open http://localhost:8000 in browser.

RunningNewDjangoPage

stop the running server and move to next step.

Enter to virtual environment

from command prompt to enter into virtual environment

workon djangoprj

EntertoVirtualEnv

Admin panel

create simple app

python manage.py startapp app

CreateDjangoApp

a new folder app has been created NewAppFolderCreated

Database

Install posgreSQL library

pip install psycopg2

InstallPsycopg2

update below database config at settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

Create model from existing database

Run below command to auto generate models. This will overwrite the exisitng models.py file.

python manage.py inspectdb > .\app\models.py

AutogenerateModelsForDjango

migration

python manage.py migrate

RunMigrate

by running the above command, few tables are created automatically. NewMigrationTablesCreated

Create super user

python manage.py createsuperuser

CreateSuperUser

Run and check

Start the server

py manage.py runserver

Go to http://localhost:8000/admin

DjangoAdminLoginScreen

stop the running server and move to next step.

Config

add app.apps.AppConfig inside INSTALLED_APPS section in settings.py file

AddAppintoSettings

Type below code admin.py file

from django.contrib import admin
from .models import Company, Medicine

# Register your models here.
admin.site.register(Company)
admin.site.register(Medicine)

RegisterModelForAdmin


Personal website and blog by M Kumaran
twittergithub