Slide 1

Slide 1 text

Django Unchained! A primer on Django framework for python web development

Slide 2

Slide 2 text

The Goals 1) Cover enough Python to get kick started with the series. 2) Enable you to explore other Pythonic stuff on your own. 3) Understand how modern web applications are engineered. 4) The Django framework. The slides and other relevant material will be available online.

Slide 3

Slide 3 text

About me ● Alumnus of this college, class of 2016. ● GSoC Mentor | GCI Mentor ● Former Software Engineer at Roadrunnr Inc. ● Currently, Mobile and User Experiences Consultant for SAP India. ● Reach me at [email protected]

Slide 4

Slide 4 text

Python Trivia ● Created by Guido Van Rossum in 1991. ● Python is an interpreted, multi-paradigm language. ● Python has no compile-time type checking of the source code. Python tracks the types of all values at runtime and flags code that does not make sense as it runs. ● ‘Batteries included’ in nature.

Slide 5

Slide 5 text

Running Python ● Interactive Interpreter – Just run python command in your terminal. You will be presented with an interactive interpreter. – Read, Eval, Print loop. ● Script Interpreter – Write a script in text editor, save it with .py extension. Run python file.py to execute. ● Console – Python -c command.

Slide 6

Slide 6 text

Python syntax and styling ● One unusual Python feature is that the whitespace indentation of a piece of code affects its meaning. ● Everything in python is an object.

Slide 7

Slide 7 text

Let’s play! ● Basic data structures. – Lists [ ] – Tuples () – Dictionaries {:} – Sets {} ● Functions, Loops and module imports. We’re not using the pythonic features yet. More on that later.

Slide 8

Slide 8 text

Running Python ● Interactive Interpreter – Just run python command in your terminal. You will be presented with an interactive interpreter. – Read, Eval, Print loop. ● Script Interpreter – Write a script in text editor, save it with .py extension. Run python file.py to execute. ● Console – Python -c command.

Slide 9

Slide 9 text

Let’s do a python primer http://bit.do/amritapy

Slide 10

Slide 10 text

Diving into web applications ● How models, views, urls and templates talk to each other to render dynamic content? ● Let’s create a “sell your products online” inventory application. ● All you need is: – Web application architecture – Models, Controllers, Views, Templates... – A decent IDE/ text editor. – Basics of python – Loops, variables, lists, dictionaries ...

Slide 11

Slide 11 text

What is Django? ● A web framework. What is a web framework? ● Django as a framework comes with – Object Relational Mapper (ORM) – URL routing – Front-end templating – Form handling – Unit testing tools – A lot others...

Slide 12

Slide 12 text

Django is NOT ● A web server ● A single language web framework ● A collection of python modules ● A packaging tool – “Python Installer of Packages” Make sure you have pip installed before we proceed further.

Slide 13

Slide 13 text

Installing Django ● http://djangoproject.com ● pip install django==1.8 ● Django-admin --version

Slide 14

Slide 14 text

Creating our first project ● Cd to the directory you want to work with. ● django-admin startproject firstdjango ● Let’s explore! ● cd firstdjango/ ● python manage.py – to list the available sub- commands. ● Python manage.py runserver

Slide 15

Slide 15 text

Generated files ● __init__.py – Tells django where the project folder is. Differentiate from app folders ● Manage.py – Run commands ● Firstdjango/wsgi.py – Used by the web server to run ● Firstdjango/settings.py – Configures Django ● Firstdjango/urls.py – Routes requests based on URL

Slide 16

Slide 16 text

Django App vs Django Project ● Within Django App is a component. ● Each App fits a specific purpose. ● Blog, Forum, Wiki, Cart, Products… ● Models.py – Data Layer, admin.py – Administrative Interface, Views.py – Control Layer, tests.py – Tests the app, migrations/ – Holds the migration files.

Slide 17

Slide 17 text

Our firstapp ● Cd to the project ● Python manage.py startapp firstapp ● Need to edit settings.py to add a new project. INSTALLED_APPS

Slide 18

Slide 18 text

Exploring settings.py ● INSTALLED_APPS ● TEMPLATES ● STATICFILES_DIRS ● DEBUG ● DATABASES

Slide 19

Slide 19 text

Inventory App – Models ● Rename firstapp to inventory ● Change the same in the settings.py ● Models create the data layer of an app ● Defines the database structure ● A model is a class inheriting from django.db.models.Model and is used to define fields as class attributes.

Slide 20

Slide 20 text

Inventory App. ● Store items with a title, description, and amount of stock. ● Allow administrators to create, edit, or delete items. ● Allow users to see a list of items in stock, with details.

Slide 21

Slide 21 text

Models.py From django.db import models class Item(models.Model): title = models.CharField(max_length=200) description = models.TextField() amout = model.IntegerField()

Slide 22

Slide 22 text

Other field types ● IntegerField, DecimalField ● CharField (needs max_length), TextField, EmailField, URLField. ● FileField, ImageField. ● BooleanField, DateTimeField

Slide 23

Slide 23 text

Field Attribute Options ● max_length ● Null = true ● Blank = true ● Default ● choices

Slide 24

Slide 24 text

Migrations ● When a model is added, a migration is required. ● Migrations – Generate scripts to change the database structure. ● Adding a model ● Adding a field ● Removing a field ● Changing the attribute of a field

Slide 25

Slide 25 text

Running Migrations ● Python manage.py makemigrations ● Python manage.py migrate –list ● Python manage.py migrate ● db.sqlite3!

Slide 26

Slide 26 text

The Django Admin Site ● Admin.py from django.contrib import admin from .models import Item class ItemAdmin(admin.ModelAdmin): list_display = [‘title’, ‘amount’] admin.site.register(Item, ItemAdmin) ● We need to have a superuser to access admin python manage.py createsuperuser

Slide 27

Slide 27 text

The ORM queries ● Runserver ● /admin ● Add Item, Editing and deleting. ● Python Interactive Shell: from inventory.models import Item items = Item.objects.all() item = item[0] item.title item.id Item.objects.get(id=1).title Item.objects.filter(amout=0) Item.objects.exclude(amout=0) Item.objects.exclude(amout=0)[0].title

Slide 28

Slide 28 text

Web Application Architecture ● URL Patterns → Views → Templates ● Models ← Views ● / → index → index.html ● /item/1/ → item_detail → item_detail.html

Slide 29

Slide 29 text

URL Patterns ● \d → single digit char ● \d+ → one or more digits ● ^admin/ → begins with admin/ ● Suffix$ → ends with suffix ● ^$ → empty strings

Slide 30

Slide 30 text

Urls.py From django.conf.urls import url from inventory import views urlpatterns = [ url(r’^$’, views.index, name=’index’), url(r’^item/(?P\d+)/’, views.item_detail, name=’item_detail’), ]

Slide 31

Slide 31 text

Views.py ● From django.http import HttpResponse def index(request): return HttpResponse(‘

In Index View

’) def item_detail(request, id): return HttpResponse(‘

In Item_detail with id {0}

’.format(id)) ● Run the server

Slide 32

Slide 32 text

Django Views ● See the complete View file. ● Index all the items in stock with items = Item.objects.exclude(amout=0) return render(request, ‘inventory/index.html’, { ‘items’: items, }) ● Item_details gets the item instance.

Slide 33

Slide 33 text

Item details view Try: item = Item.objects.get(id=id) except Item.DoesNotExist: railse Http404(‘This item does not exist’) return render(request, ‘inventory/item_detail.html’, { ‘item’ : item, })

Slide 34

Slide 34 text

Templates ● Modify settings.py TEMPLATES → DIRS: [‘firstdjango/templates’] ● Create a directory called templates, then create an inventory directory, make index.html and item_detail.html ● Put a couple of

tags and see if templates are working fine.

Slide 35

Slide 35 text

Template Tags ● {{ variable }} ● {% tag %} ● {{ variable | filter }} ●

{{ item.title }}

● {% for item in items %}
  • {{ item.title }}
  • {% endfor %} ● {% url ‘index’ %} ● {% url ‘item_detail’ item.id %} ●

    {{ item.title | capfirst }}

    Slide 36

    Slide 36 text

    The completed templates ● Template inheritance ● Future-proofing ● Block tag overriding

    Slide 37

    Slide 37 text

    Project files are at https://github.com/raincrash/PythonCourse

    Slide 38

    Slide 38 text

    Questions