Accelerating Information Technology Innovation

Similar documents
South Africa Templates.

Django: Views, Templates, and Sessions

정재성

MIT AITI Python Software Development Lab DJ1:

CE419 Web Programming. Session 15: Django Web Framework

Accelerating Information Technology Innovation

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

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

Django Synctool Documentation

The Django Web Framework Part II. Hamid Zarrabi-Zadeh Web Programming Fall 2013

Graphene Documentation

django-model-report Documentation

Accelerating Information Technology Innovation

Django urls Django Girls Tutorial

Quoting Wikipedia, software

webkitpony Documentation

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

django-avatar Documentation

django-avatar Documentation

silk Documentation Release 0.3 Michael Ford

Django starting guide

wagtail-robots Documentation

Django Part II SPARCS 11 undead. Greatly Inspired by SPARCS 10 hodduc

Accelerating Information Technology Innovation

Linguistic Architecture

Rapid Development with Django and App Engine. Guido van Rossum May 28, 2008

Django Web Framework: A Comprehensive Introduction and Step by Step Installation

django-conduit Documentation

django-mongonaut Documentation

Accelerating Information Technology Innovation

canary Documentation Release 0.1 Branton K. Davis

The syndication feed framework

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

Django IPRestrict Documentation

Tablo Documentation. Release Conservation Biology Institute

Django-Select2 Documentation. Nirupam Biswas

DJOAuth2 Documentation

Back-end development. Outline. Example API: Chatter. 1. Design an example API for Chatter. Tiberiu Vilcu.

Framework approach to building content management systems. Wednesday, February 20, 13

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.

Building a Django Twilio Programmable Chat Application

django-openid Documentation

Tastypie Documentation

Bambu API Documentation

django-scaffold Documentation

Diving into Big Data Workshop

Django File Picker Documentation

django-permission Documentation

django-oauth2-provider Documentation

Tailor Documentation. Release 0.1. Derek Stegelman, Garrett Pennington, and Jon Faustman

cmsplugin-blog Release post 0 Øyvind Saltvik

Lightweight. Django USING REST, WEBSOCKETS & BACKBONE. Julia Elman & Mark Lavin

Django File Picker Documentation

django-simple-sms Documentation

django-mama-cas Documentation

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

Tangent MicroServices Documentation

open-helpdesk Documentation

django-users2 Documentation

CSE 115. Introduction to Computer Science I

django-dajaxice Documentation

MIT Global Startup Labs México 2013

HOW TO FLASK. And a very short intro to web development and databases

django-ratelimit-backend Documentation

Lecture 10(-ish) Web [Application] Frameworks

ASP.NET State Management Techniques

CSC Web Programming. Introduction to SQL

Bricks Documentation. Release 1.0. Germano Guerrini

Djam Documentation. Release Participatory Culture Foundation

django-rest-framework-datatables Documentation

django-facetools Documentation

e-submission System User Manual Publication Related Matters

Django MFA Documentation

Django Groups Manager Documentation

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

Forms iq Designer Training

Web Development & SEO (Summer Training Program) 4 Weeks/30 Days

Django Deployment & Tips daybreaker

django-revproxy Documentation

fragapy Documentation

Django REST Framework JSON API Documentation

Tastypie Documentation

SAURASHTRA UNIVERSITY

Spade Documentation. Release 0.1. Sam Liu

alphafilter Documentation

django-subdomains Documentation

generates scaffolding/framework for models, views

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

VUEWorks Report Generation Training Packet

INTRODUCTION TO DATABASES IN PYTHON. Filtering and Targeting Data

Django_template3d Documentation

***** Archive and Backup your Data before updating***** ****Ensure that you are running a minimum version of before updating****

Django Phantom Theme Documentation

SSC - Web applications and development Introduction and Java Servlet (I)

Django Hordak Documentation

django-password-reset Documentation

django-storages Documentation

Unit Assessment Guide

Tobacco Products Manufacturer s and Importer s Report

Django Test Utils Documentation

Transcription:

Accelerating Information Technology Innovation http://aiti.mit.edu Ghana Summer 2012 Lecture DJ04 Django Views

Simple Diagram HTTP Request Browser urls.py HTTP Request Model/Database Data Request Data View HTTP Response

Web Browsing Users submit requests to websites through: Desktop web browsers and applications Smartphone web browsers and applications Django calls a view function associated with the URL User defines a map between the URL and the view function

Simple Diagram HTTP Request Browser urls.py HTTP Request Model/Database Data Request Data View HTTP Response

Hello World! Django Sample URLConf and view function below hello_world/urls.py from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('', url(r ^$', views.hello_world ) hello_world/views.py from django.http import HttpResponse def hello_world(request): return HttpResponse( Hello world! )

Hello World! Django Letʼs see the results! python manage.py runserver Cool! How do we make more exciting websites? Models- Store useful information Templates- Produce dynamic pages Views- We can do a lot more than Hello world!

Checkpoint Which file should we modify (and how) if we want to see Hello World! at the following URL? http://127.0.0.1:8000/hello_world Which file(s) should we modify (and how) if we want to see Hello Mars at the following URL? http://127.0.0.1:8000/hello_mars

Views How can we customize the view? parameters from the URL (regexps)

Views Parameters in the URL Regular Expressions specify the rules for URL s Resources available online to learn more Consider a universal greeting: urlpatterns = patterns(, url(r'^hello_(? P<planet>\w+)/$', 'views.hello_anyone'), )

Views Universal greeting urlpatterns = patterns(', url(r'^(hello)_w+/$', 'views.hello_anyone'), ) Our view function has two parameters request (HttpRequest object) planet (string object) from django.http import HttpResponse def hello_anyone(request,planet): my_response = "Hello + str(planet) return HttpResponse(my_response)

Views Testing it out

Database Interaction We want to be able to display information from our database tables as well!

Getting all data Blog.objects.all() Gets all the data associated with the model but does NOT execute the query It s not a list, it s an instance of QuerySet

Filtering Data exact: gets an exact match Blog.objects.filter(title exact='cool') Blog.objects.filter(title='cool') # exact is implied contains: find if a match is contained inside a field Blog.objects.filter (blog_text contains='cool') icontains: case insensitive contains Blog.objects.filter (author icontains='smith') More here: https://docs.djangoproject.com/en/1.3/ref/models/querysets/ #field-lookups

Ordering Blog.objects.order_by('-pub_date', 'title') First orders by pub_date in descending order (hence the negative sign). If there are pub_dates that are equivalent, then title is ordered in ascending order.

Values Blog.objects.values() Returns a ValueQuerySet, which returns a list of dictionaries when executed Blog.objects.values('title', 'body') Returns only the fields title and body in the dictionary # This list contains a Blog object. >>> Blog.objects.filter(name startswith='beatles') [<Blog: Beatles Blog>] # This list contains a dictionary. >>> Blog.objects.filter (name startswith='beatles').values() [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]

Distinct Blog.objects.distinct() If there are any duplicate rows, only one is returned This will rarely work like this, because you often will already have a distinct field, like an id Blog.objects.distinct('title', 'body') This will get all unique title-body combinations

Slicing Blog.objects.all()[:5] Gets the first 5 blog objects The limit happens in the sql query ex: SELECT * FROM users LIMIT 5

Get Gets a single row raises MultipleObjectsReturned if more than one object was found. raises a DoesNotExist exception if an object wasn't found for the given parameters.

Get continued Blog.objects.get(id=5) Returns a single QuerySet if there is a row that exists, otherwise an error ensues Blog.objects.filter(id=5)[0] Similar, except no exceptions are thrown

When are QuerySets Evaluated? Iteration for e in Entry.objects.all(): print e.headline Boolean if Entry.objects.filter(headline="Test"): print "There is at least one Entry with the headline Test"

Lookups that span relationships Blog.objects.filter (comment title contains='lennon') Retrieves all Blog objects with a comment whose title contains 'Lennon'

Views Example def get_titles(request, limit=100): book_list = Book.objects.all()[:limit] response = List of titles is: for b in book_list: response+=str(b.title) return HttpResponse(response)