CE419 Web Programming. Session 15: Django Web Framework

Similar documents
MIT Global Startup Labs México 2013

Webdev: Building Django Apps. Ryan Fox Andrew Glassman MKE Python

Accelerating Information Technology Innovation

django-model-utils Documentation

Graphene Documentation

staff Documentation Release 1.2

South Documentation. Release 1.0. Andrew Godwin

Reminders. Full Django products are due next Thursday! CS370, Günay (Emory) Spring / 6

South Africa Templates.

django-audit-log Documentation

Lecture 10(-ish) Web [Application] Frameworks

Accelerating Information Technology Innovation

Bricks Documentation. Release 1.0. Germano Guerrini

Django-dbindexer Documentation

django-modeltranslation Documentation

L6 Application Programming. Thibault Sellam Fall 2018

Accelerating Information Technology Innovation

Tomasz Szumlak WFiIS AGH 23/10/2017, Kraków

generates scaffolding/framework for models, views

django-conduit Documentation

PART I SQLAlchemy Core

django-filter Documentation

DDF Documentation. Release Paulo Cheque

정재성

Runtime Dynamic Models Documentation Release 1.0

MIT AITI Python Software Development Lab DJ1:

Django Admin Sortable Documentation

Django starting guide

Easy-select2 Documentation

Django IPRestrict Documentation

django-filter Documentation

Moving to a Sustainable Web Development Environment for Library Web Applications

7401ICT eservice Technology. (Some of) the actual examination questions will be more precise than these.

django-pgfields Documentation

Bishop Blanchet Intranet Documentation

The simple but powerful elegance of Django REST Framework. start

Django Image Tools Documentation

Django File Picker Documentation

Django CBTools Documentation

COMP 430 Intro. to Database Systems. SQL from application code

neo4django Documentation

Django Extras Documentation

widgets, events, layout loosely similar to Swing test browser, or plugin for testing with real browser on local system

django-scaffold Documentation

django-oauth2-provider Documentation

canary Documentation Release 0.1 Branton K. Davis

Django Extra Views Documentation

django-mongonaut Documentation

Accelerating Information Technology Innovation

django-auditlog Documentation

Linguistic Architecture

Quoting Wikipedia, software

LECTURE 21. Database Interfaces

Technology modeling. Ralf Lämmel Software Languages Team University of Koblenz-Landau

Lotus IT Hub. Module-1: Python Foundation (Mandatory)

web.py Tutorial Tom Kelliher, CS 317 This tutorial is the tutorial from the web.py web site, with a few revisions for our local environment.

Django-Select2 Documentation. Nirupam Biswas

wagtailtrans Documentation

Django ORM Cookbook Documentation

django-data-migration Documentation

dango-ct Documentation

django IN DEPTH JAMES BENNETT PYCON MONTRÉAL 9TH APRIL 2015

django-permission Documentation

Python Schema Generator Documentation

Python. Django. (Web Application Framework - WAF) PyCharm. (Integration Development Environment - IDE)

django-image-cropping Documentation

Puzzlehunt Server Documentation

django-model-report Documentation

Topics. History. Architecture. MongoDB, Mongoose - RDBMS - SQL. - NoSQL

django-audiofield Documentation

Django 1.9 and PostgreSQL

Transactions for web developers

Develop Python Applications with MySQL Connector/Python DEV5957

django-polymorphic Documentation

django-slim Documentation

Flask-MongoEngine Documentation

9 Common Patterns for Forms

SQL Data Definition Language: Create and Change the Database Ray Lockwood

The Definitive Guide to Django

Database &.NET Basics: Take what you know about SQL and apply that to SOQL, SOSL, and DML in Apex.

web frameworks design comparison draft - please help me improve it focus on Model-View-Controller frameworks

Django REST Framework JSON API Documentation

EE221 Databases Practicals Manual

Aristotle Metadata Registry Documentation

Django ORM crash

Paris Documentation. Release. Jamie Matthews and Simon Holywell

django-gollum Documentation

django-cron Documentation

Django Localized Recurrence Documentation

COMP 430 Intro. to Database Systems. Encapsulating SQL code

Building a Django Twilio Programmable Chat Application

kiss.py Documentation

CSV Importer Documentation

Asynchronous WebSockets using Django

Mixer Documentation. Release Kirill Klenov

Rails: MVC in action

Dobby Documentation. Release 0.1. Antoine Bertin

django-celery Documentation

django-mailbox Documentation

django-filer Documentation

Transcription:

CE419 Web Programming Session 15: Django Web Framework

Web Applications & Databases In modern Web applications, the arbitrary logic often involves interacting with a database. Behind the scenes, a database-driven Web site connects to a database server, retrieves some data out of it, and displays that data on a Web page. The site might also provide ways for site visitors to populate the database on their own.

Web Applications & Databases Amazon.com, for instance, is a great example of a database-driven site. Each product page is essentially a query into Amazon s product database formatted as HTML. When you post a customer review, it gets inserted into the database of reviews. Django is well suited for making database-driven Web sites, because it comes with easy yet powerful tools for performing database queries using Python.

Databases: The Dumb Way import MySQLdb def book_list(request): db = MySQLdb.connect(user='me', db='mydb', passwd='secret', host='localhost') cursor = db.cursor() 3 2 cursor.execute('select name FROM books ORDER BY name') names = [row[0] for row in cursor.fetchall()] db.close() 1 # let's do the rest here.

Databases: The Not-So-Dumb Way ORM comes to the rescue! from mysite.books.models import Book def book_list(request): books = Book.objects.order_by('name') # tada!

Models in Django A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you re storing. Generally, each model maps to a single database table. Each model is a Python class that subclasses django.db.models.model. Each attribute of the model represents a database field.

Configuring the Database First, we need to take care of some initial configuration; we need to tell Django which database server to use and how to connect to it. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } }

SQLite In contrast to other database management systems, SQLite is not a client server database engine. Rather, it is embedded into the end program. Good for development and small projects.

Quick Example from django.db import models class Person(models.Model): first_name = models.charfield(max_length=30) last_name = models.charfield(max_length=30) CREATE TABLE myapp_person ( "id" serial NOT NULL PRIMARY KEY, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL );

Using Models Once you have defined your models, you need to tell Django you re going to use those models. Do this by editing your settings file and changing the INSTALLED_APPS setting to add the name of the module that contains your models.py. INSTALLED_APPS = ( #... 'myapp', #... ) python manage.py migrate

Fields The most important part of a model and the only required part of a model is the list of database fields it defines. Fields are specified by class attributes. from django.db import models class Post(models.Model): title = models.charfield(max_length=255) body = models.textfield() author = models.foreignkey(user) publish_date = models.datetimefield()

Field Types Each field in your model should be an instance of the appropriate Field class. Some of builtin field types in Django: CharField, TextField, DateField, DateTimeField, EmailField, FileField, URLField, etc. Complete list: https://docs.djangoproject.com/en/1.8/ref/models/ fields/ You can subclass Field and create your custom types! For example, PersianDateField.

Field Options Each field takes a certain set of field-specific arguments. CharField requires max_length. There s also a set of common arguments available to all field types. All are optional.

Field Options (cont'd) null If True, Django will store empty values as NULL in the database. Default is False. blank If True, the field is allowed to be blank. Default is False. Difference between blank and null?

Field Options (cont'd) default The default value for the field. This can be a value or a callable object. unique If True, this field must be unique throughout the table.

Field Options (cont'd) import datetime from django.db import models class Post(models.Model): # title = models.charfield(max_length=255, unique=true) excerpt = models.textfield(null=true, blank=true) publish_date = models.datetimefield(default=datetime.datetime.now) #

Automatic Primary Key Fields By default, Django gives each model the following field: id = models.autofield(primary_key=true) If you d like to specify a custom primary key, just specify primary_key=true on one of your fields. If Django sees you ve explicitly set Field.primary_key, it won t add the automatic id column.

Relationships Clearly, the power of relational databases lies in relating tables to each other. Django offers ways to define the three most common types of database relationships: many-to-one, many-tomany and one-to-one.

Many-to-One Relationships from django.db import models class Manufacturer(models.Model): #... pass class Car(models.Model): manufacturer = models.foreignkey(manufacturer) #... 2 1

Many-to-Many Relationships It doesn t matter which model has the ManyToManyField, but you should only put it in one of the models not both. "More Natural" from django.db import models class Track(models.Model): #... pass class Playlist(models.Model): tracks = models.manytomanyfield(track) #... 2 1

One-to-One Relationships For example, if you were building a database of places, you would build pretty standard stuff such as address, phone number, etc. in the database. Then, if you wanted to build a database of restaurants on top of the places, instead of repeating yourself and replicating those fields in the Restaurant model, you could make Restaurant have a OneToOneField to Place.

Making Database Queries Once you ve created your data models, Django automatically gives you a database-abstraction API that lets you create, retrieve, update and delete (CRUD) objects. A model class represents a database table, and an instance of that class represents a particular record in the database table. python manage.py shell

Creating Objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. from blog.models import Author author = Author(name="Sadjad Fouladi", email="sfouladi@gmail.com") author.save() 2 1 author.email = "fouladi@ce.sharif.edu" author.save() 3

Saving ForeignKey and ManyToManyField Fields Updating a ForeignKey field works exactly the same way as saving a normal field simply assign an object of the right type to the field in question. Updating a ManyToManyField works a little differently use the add() method on the field to add a record to the relation.

Retrieving Objects To retrieve objects from your database, construct a QuerySet via a Manager on your model class. A QuerySet represents a collection of objects from your database. It can have zero, one or many filters. In SQL terms, a QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT.

Retrieving Objects (cont'd) Retrieving all objects all_entries = Entry.objects.all() Filtering and excluding q1 = Entry.objects.filter(rating=4) q2 = Entry.objects.exclude(rating lt=3) q3 = Entry.objects.filter(headline contains='book', rating=5, pub_date year=2011)

Chaining Filters The result of refining a QuerySet is itself a QuerySet, so it s possible to chain refinements together. q1 = Entry.objects.filter( rating=4 ).filter( headline contains="book" ).exclude( pub_date year=2013 )

Querysets Are Lazy >>> q = Entry.objects.filter(headline startswith="what") >>> q = q.filter(pub_date lte=datetime.date.today()) >>> print(q) 29

Retrieving a Single Object DoesNotExist, MultipleObjectsReturned. one_entry = Entry.objects.get(id=1)

Limiting QuerySets What if the QuerySet matches 1,000 objects?! Entry.objects.all()[:5] Entry.objects.filter( )[15:30] Equivalent of SQL s LIMIT and OFFSET clauses.

Field Lookups Field lookups are how you specify the meat of an SQL WHERE clause. They re specified as keyword arguments to the QuerySet methods filter(), exclude() and get(). field lookuptype=value exact, iexact, contains, icontains, startswith, endswith, lt, gt, lte, gte, and A LOT more.

Deleting and Updating Objects Entry.objects.filter( rating=4 ).update(rating=5) Entry.objects.filter(rating lte=2).delete()

Django Admin One of the most powerful parts of Django is the automatic admin interface. Let's see Django admin for our project!

Thank you. Any questions? 38