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

Similar documents
Django: Views, Templates, and Sessions

Django urls Django Girls Tutorial

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

MIT AITI Python Software Development Lab DJ1:

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

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

Accelerating Information Technology Innovation

정재성

Django starting guide

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

Django. Jinja2. Aymeric Augustin DjangoCong 2016

Accelerating Information Technology Innovation

Code editor Django Girls Tutorial

Djam Documentation. Release Participatory Culture Foundation

Moving to a Sustainable Web Development Environment for Library Web Applications

django-cms-search Documentation

django-scaffold Documentation

Graphene Documentation

django-rest-framework-datatables Documentation

Linguistic Architecture

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

LECTURE 14. Web Frameworks

Course Title: Python + Django for Web Application

Web Application Architectures

wagtail-robots Documentation

webcore Documentation

django-avatar Documentation

Django Phantom Theme Documentation

django-avatar Documentation

django-intercom Documentation

Quick housekeeping Last Two Homeworks Extra Credit for demoing project prototypes Reminder about Project Deadlines/specifics Class on April 12th Resul

Introduction to WEB PROGRAMMING

Session 4. Style Sheets (CSS) Reading & References. A reference containing tables of CSS properties

2. Write style rules for how you d like certain elements to look.

django-session-security Documentation

MapEntity Documentation

Django IPRestrict Documentation

Bambu API Documentation

Python Web Development With Django By Paul Bissex, Jeff Forcier

8/19/2018. Web Development & Design Foundations with HTML5. Learning Objectives (1 of 2) More on Relative Linking. Learning Objectives (2 of 2)

django-amp-tools Documentation Release latest

Styles, Style Sheets, the Box Model and Liquid Layout

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

LECTURE 14. Web Frameworks

django-sekizai Documentation

Assignments (4) Assessment as per Schedule (2)

Django Deployment & Tips daybreaker

colab Documentation Release 2.0dev Sergio Oliveira

DJOAuth2 Documentation

django-subdomains Documentation

South Africa Templates.

CSCI 1320 Creating Modern Web Applications. Content Management Systems

About the Tutorial. Audience. Prerequisites. Disclaimer & Copyright. Django

Building a Python Flask Website A beginner-friendly guide

Introduction to Computer Science Web Development

Lab 1: Introducing HTML5 and CSS3

django-sticky-uploads Documentation

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

alphafilter Documentation

cmsplugin-blog Release post 0 Øyvind Saltvik

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

Django Test Utils Documentation

Taking Fireworks Template and Applying it to Dreamweaver

Django with Python Course Catalog

Quoting Wikipedia, software

django-baton Documentation

django-openid Documentation

CIS192 Python Programming

HTMLnotesS15.notebook. January 25, 2015

django-facebook-graph Documentation

Accelerating Information Technology Innovation

Index. alt, 38, 57 class, 86, 88, 101, 107 href, 24, 51, 57 id, 86 88, 98 overview, 37. src, 37, 57. backend, WordPress, 146, 148

ADDING CSS TO YOUR HTML DOCUMENT. A FEW CSS VALUES (colour, size and the box model)

Lecture 10(-ish) Web [Application] Frameworks

Django_template3d Documentation

Bambu Bootstrap Documentation

django-xross Documentation

Building a Django Twilio Programmable Chat Application

wagtailtrans Documentation

welcome to BOILERCAMP HOW TO WEB DEV

django-baton Documentation

SASS Variables and Mixins Written by Margaret Rodgers. Variables. Contents. From Web Team. 1 Variables

micawber Documentation

Problem Description Earned Max 1 HTML / CSS Tracing 20 2 CSS 20 3 PHP 20 4 JS / Ajax / JSON 20 5 SQL 20 X Extra Credit 1 TOTAL Total Points 100

Pluggable Patterns. For Reusable Django Applications

Microsoft Expression Web Quickstart Guide

Nuit Documentation. Release Ben Cardy

kiss.py Documentation

django-contact-form Documentation

The syndication feed framework

Responsive web design (RWD) CSS3 Media queries. Mobile vs desktop web sites. Web Development 1 CS1115/CS5002

django-intranet Documentation

Create a three column layout using CSS, divs and floating

Page Layout. 4.1 Styling Page Sections 4.2 Introduction to Layout 4.3 Floating Elements 4.4 Sizing and Positioning

generates scaffolding/framework for models, views

TRAINING GUIDE. ArcGIS Online and Lucity

The Definitive Guide to Django

Fundamentals of Web Technologies. Agenda: CSS Layout (Box Model) CSS Layout: Box Model. All HTML elements can be considered as a box or a container

ska Documentation Release Artur Barseghyan

django-image-cropping Documentation

Transcription:

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

2 Outline Overview Making the Front Page Creating the Template Creating View Functions Configuring URL Patterns Finishing Touches Wrap It Up

3 Overview We will continue the Blog application What we did in last session: installed Django created the project mysite created the Blog app, and added it to the project designed our model, BlogPost, and synced it to the db set up the admin site, and registered our model onto it started entering data

4 Overview (cont'd) Today, we will focus on building the blog's public interface, namely its front page A page in Django has three typical components A template that displays information passed to it (in a Python-dictionary-like object called a Context) A view function that fetches information to be displayed, typically from a database A URL pattern that matches an incoming request with your view function, optionally passing parameters to the view as well

Making the Front Page

6 Creating a Template This is a simple template for displaying a single blog post: <h2>{{ post.title }}</h2> <p>{{ post.timestamp }}</p> <p>{{ post.body }}</p> It s just HTML, plus special template tags in curly braces Django templates can be indeed used for any kind of textual output We store templates inside blog/templates/[blog]

7 Template Variable Tags In the previous example, we had three variable tags Inside a variable tag, you can use Python-style dot-notation to access attributes of the objects passed to the template For example, previous template assumes you have passed it a BlogPost object called post The three lines of the template fetch the BlogPost object s title, timestamp, and body fields, respectively

8 Template Code Tags We can enhance the template to display multiple blog posts, using for block tag Unlike variable tags, block tags are enclosed in {%... %} pairs {% for post in posts %} <h2>{{ post.title }}</h2> <p>{{ post.timestamp date:'l, F js' }}</p> <p>{{ post.body }}</p> {% endfor %}

9 Creating a View Function Now we write a view function that fetches all our blog posts from the database, and displays them using our template from django.template import loader, Context from django.http import HttpResponse from blog.models import BlogPost def index(request): posts = BlogPost.objects.all() template = loader.get_template('index.html') context = Context({ 'posts': posts }) return HttpResponse(template.render(context))

10 Rendering Shortcut It is a very common idiom to load a template, fill a context and return an HttpResponse object with the result of the rendered template Django provides a shortcut, called render from django.shortcuts import render from blog.models import BlogPost def index(request): posts = BlogPost.objects.all() context = { 'posts': posts } return render(request, 'index.html', context)

11 Creating a URL Pattern The last piece needed for our page to work is a URL We can create the needed URL pattern inside the blog package at blog/urls.py from django.conf.urls import patterns, url from blog import views urlpatterns = patterns('', url(r'^$', views.index, name='index') )

12 Point the Root URLconf The last step is to modify the root URLconf at mysite/urls.py to include blog/urls.py from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), )

13 Try It Out The page is now ready to see in action at http://localhost:8000/blog/

Finishing Touches

15 Base Templates Our previous template was simplistic and selfcontained Most often, we have several pages in our app, and we want all of them to be based on a common template The right way in Django is to create a base template, and then extend this template to generate the other, specific templates

16 Base Template: Example Here is a sample base template <html> <style type="text/css"> body { color: #ccc; background: #000; padding: 0 5em; margin: 0 } h1 { padding: 1em; background: #675 } h2 { color: #bf8; border-top: 1px dotted #fff; margin-top: 2em } p { margin: 1em 0 } </style> <body> <h1>my Blog</h1> {% block content %} {% endblock %} </body> </html>

17 Extending Base Template We can now define our template by extending the base {% extends "base.html" %} {% block content %} {% for post in posts %} <h2>{{ post.title }}</h2> <p>{{ post.timestamp }}</p> <p>{{ post.body }}</p> {% endfor %} {% endblock %}

18 The New Look

19 Date Ordering Our blog posts are not being presented in traditional reverse-chronological order It is easy to tell Django to do that We can either add it to the query: BlogPost.objects.all().order_by('-timestamp') Or add a default ordering to our model: class Meta: ordering = ('-timestamp',)

20 Template Filters its ISO8601 format of the dates is a little nerdy; Let s humanize it a bit using template filters To apply a filter to a variable, simply add it to the end of the variable name using a pipe character <p>{{ post.timestamp date }}</p> You can even customize the filter by passing argument to it <p>{{ post.timestamp date:'l, F js' }}</p>

Wrap It Up

22 The Big Picture Django encompasses a large number of concepts, features, and tools Before starting to learn the details, you need to grasp an overall view of the whole framework and its architecture

23 Overall Architecture

24 Core Philosophies of Django Separating the Layers (MVC) Try to Be Pythonic Don t Repeat Yourself (DRY) Loose Coupling and Flexibility Rapid Development generic views, shortcuts, middleware, etc.

25 References Django Documentation http://docs.djangoproject.com/en/ Python Web Development with Django By Jeff Forcier, Paul Bissex, Wesley Chun