Show Menu

Cheat sheet on basics of django


pip install django

Create project and lightw­eight develo­pment server

django-admin startproject <projectname>
python runserver

Create an app

python startapp <appname>

Creating views and URL mapping

# <projectname>/<appname>/
from django.http import HttpResponse
def index(request):
    return HttpResponse("Hello world")

# <projectname>/<appname>/
from django.urls import path
from . import views
urlpatterns = [ path('app', views.index, name='index'), ]

# <projectname>/ 
from django.urls import include, path
urlpatterns = [ 
    path('app/', include('app.urls'), 

Database Setup / APPLY changes to database

python migrate
synchr­onizes changes made to your models with the schema in the database.
Django tracks which migrations have already been applied with a table called
in the database

Creating models

from django.db import models

class A(models.Model): 
    name = models.charField(max_length=200)
    age = models.IntegerField(default=0)
    birthday = models.DateTimeField('birthday)' 

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    height = models.IntegerField(default=0)

Activating models

# <projectname>/

MAKE migrations for changes to models

python makemigrations <appname>

Run a sample migration

python sqlmigrate <appname> 0001

Run a check on the project

python check

Invoke Python shell

python shell

Create admin

python createsuperuse

# enter username and password for admin user

Register model in admin

# <projectname>/<appname>/

from django.contrib import admin
from .models import A


No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Python Cheat Sheet
          Django Basics Cheat Sheet