Show Menu
Cheatography

Cheat sheet on basics of django

Instal­lation

pip install django

Create project and lightw­eight develo­pment server

django-admin startproject <projectname>
python manage.py runserver

Create an app

python manage.py startapp <appname>

Creating views and URL mapping

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

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

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

Database Setup / APPLY changes to database

python manage.py migrate
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
django­_mi­gra­tions
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>/settings.py
...
INSTALLED_APPS = [ 
    'appName.apps.AppNameConfig', 
    'django.contrib.admin', 
...
]

MAKE migrations for changes to models

python manage.py makemigrations <appname>

Run a sample migration

python manage.py sqlmigrate <appname> 0001

Run a check on the project

python manage.py check
 

Invoke Python shell

python manage.py shell

Create admin

python manage.py createsuperuse

# enter username and password for admin user

Register model in admin

# <projectname>/<appname>/admin.py

from django.contrib import admin
from .models import A

admin.site.register(A)
 

Comments

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