Top Banner
Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine http://www.dbmi.pitt.edu
93

Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Dec 24, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Web Frameworks: Django

Department of Biomedical InformaticsUniversity of Pittsburgh School of Medicine

http://www.dbmi.pitt.edu

Page 2: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

The Purpose of the Lecture

Introduce the basic steps for web programming using Django.

This is done by walking you though the steps that takes to create an web blog: “jiangblog”

“jiangblog” is designed to allow a user to make comments online about some topics such as a presidential debate, and save these comments in a database.

Page 3: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Python and SQLite has to be installed before installing django!

Page 4: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Download and Install Django

1. Download Django 1.4.2 from the following website:

https://www.djangoproject.com/download/.

2. Install Django:

tar xzvf Django-1.4.2.tar.gz

cd Django-1.4.2

sudo python setup.py install

Page 5: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Create a Django Project

Django provides a utility called django-admin.py that can streamline the tasks for you when you create a django project. (Note that I use red color for the terminal output.)

xjiang-lp:django xij6$ django-admin.py startproject jiangblog

xjiang-lp:django xij6$ ls -l

total 0

drwxr-xr-x 4 xij6 PITT\domain users 136 Nov 8 11:28 jiangblog

drwxr-xr-x 7 xij6 PITT\domain users 238 Nov 8 11:05 mysite

Page 6: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Check What have been Created in jiangblog

xjiang-lp:django xij6$ cd jiangblog

xjiang-lp:jiangblog xij6$ ls -l

total 8

drwxr-xr-x 6 xij6 PITT\domain users 204 Nov 8 11:28 jiangblog

-rwxr-xr-x 1 xij6 PITT\domain users 252 Nov 8 11:28 manage.py

xjiang-lp:jiangblog xij6$

Page 7: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Check What have been Created in jiangblog

xjiang-lp:jiangblog xij6$ ls -l jiangblog

total 32

-rw-r--r-- 1 xij6 PITT\domain users 0 Nov 8 11:28 __init__.py

-rw-r--r-- 1 xij6 PITT\domain users 5221 Nov 8 11:28 settings.py

-rw-r--r-- 1 xij6 PITT\domain users 565 Nov 8 11:28 urls.py

-rw-r--r-- 1 xij6 PITT\domain users 1140 Nov 8 11:28 wsgi.py

Page 8: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

The Files Created by Django-Admin.py startproject

manage.py: Command-line interface for applications.

__init__.py: Specifies to Python that this is a package.

urls.py: Global URL configuration (“URLconf”).

settings.py: Project-specific configuration

wsgi.py: ???

Page 9: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

The “pure Python” philosophy

Note that every file created by the startproject command is Python code with an extension .py

Django tries to stay with Python code wherever possible. This certainly reduces the complexity to the framework for a python programmer.

Page 10: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Running the Development Server

The development server is a server designed for the development phase that runs on your local computer. xjiang-lp:jiangblog xij6$ python ./manage.py runserver

Validating models…

0 errors found

Django version 1.4.2, using settings 'jiangblog.settings'

Development server is running at http://127.0.0.1:8000/

Quit the server with CONTROL-C.

Error: [Errno 48] Address already in use

Page 11: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Running the Development Server

Note that if you want to run your server on a different port, you can specify that on the command line:

python ./manage.py runserver

Page 12: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

xjiang-lp:jiangblog xij6$ ./manage.py runserver 8080

Validating models...

0 errors found

Django version 1.4.2, using settings 'jiangblog.settings'

Development server is running at http://127.0.0.1:8080/

Quit the server with CONTROL-C.

Page 13: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 14: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

DBMIAdmins-MacBook-Pro:jiangblog xij6$ ./manage.py startapp presdebate

DBMIAdmins-MacBook-Pro:jiangblog xij6$ ls -l

total 8

drwxr-xr-x 10 xij6 PITT\domain users 340 Nov 8 12:32 jiangblog

-rwxr-xr-x 1 xij6 PITT\domain users 252 Nov 8 11:28 manage.py

drwxr-xr-x 6 xij6 PITT\domain users 204 Nov 8 13:33 presdebate

DBMIAdmins-MacBook-Pro:jiangblog xij6$

Page 15: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Create an Application within a Project

We want to create an application named as “presdebate”, which can be used to collect comments from web users about a presidential debate.

./manage.py startapp presdebate

Page 16: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Again, we want to know what files have been created for our application.

DBMIAdmins-MacBook-Pro:jiangblog xij6$ ls -l presdebate

total 24

-rw-r--r-- 1 xij6 PITT\domain users 0 Nov 8 13:33 __init__.py

-rw-r--r-- 1 xij6 PITT\domain users 57 Nov 8 13:33 models.py

-rw-r--r-- 1 xij6 PITT\domain users 383 Nov 8 13:33 tests.py

-rw-r--r-- 1 xij6 PITT\domain users 26 Nov 8 13:33 views.py

DBMIAdmins-MacBook-Pro:jiangblog xij6$

Page 17: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

The Files Created for our Application “presdebate”

__init__.py: Specifies to Python that this is a package

models.py: Data models

views.py: view functions

tests.py: unit tests

What is missing?

urls.py: The app’s URL configuration (“URLconf”). This is not automatically created.

Page 18: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

To inform Django that the new app “presdebate” is part of our project, we need to edit settings.py.

We need to open the settings.py with an editor and find the INSTALLED_APPS tuple near the bottom, then add our application name (presdebate) as a member of that tuple.

In Mac I typically use either textmate or coda2 to do the editing work.

Page 19: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

NSTALLED_APPS after editing

Page 20: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Creating a Data ModelWe need to create a data model via editing the file called models.py, which is automatically generated for application presdebate.

This data model defines the data structures of presdebate.

Django provides a variety of fields that map to our application data.

In application presdebate, we will use three different field types.

Page 21: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Models.py before editing

Page 22: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Models.py after editing

Page 23: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

The newly created class, PresDebate, is a subclass of django.db.models.Model.

That’s Django standard base class for data models, which is the core of Django’s powerful ORM.

The fields are defined like regular class attributes, with each one being an instance of a particular field class.

Page 24: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

A CharField is appropriate for short, single lines of text.

A TextField type is good for a large chunk of text, such as a large paragraph of comments we may collect from a user.

A DateTimeField is represented by a Python datetime.datetime object.

For a list of field types provided by Django, refer to the documentation at:

https://docs.djangoproject.com/en/dev/ref/models/fields/#field-types

Page 25: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Setting Up the Database

Using SQLite with the local host, you only need to do two things:

1.Update the engine.

2. Specify the name (use full pathname to avoid confusion) of the database that will be created in the settings.py file.

Page 26: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

DATABASES entry in settings.py before editing

Page 27: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

“DATABASES”entry in settings.py after editing

Page 28: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Setting Up the Database

Now we need to tell Django to use the information (the pathname of our database) you’ve given it to connect to the database and set up tables that our application needs.

We use the syncdb command of manage.py to do this.

Page 29: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 30: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Setting Up the Database

When the syncdb command is issued, Django looks for a models.py file in each of the INSTALLED_APPS entry.

For each model it finds, it creates a database table.

Adding a super user is useful, especially when we add the Django’s automatic admin application later.

Page 31: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 32: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Creating the predebate’s User Interface

With Django, a Web page has the following typical components:

1.A template that defines how it looks, and displays information passed to it.

2. A view function that performs the core logic for a request, fetch the information to be displayed from a database, and store new information entered by a users to the database.

Page 33: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Creating the Predebate’s User Interface

3. A URL pattern that matches an incoming request with the corresponding view.

We will build our application according to the following order:

1.Build a template.

2.Design an Url Pattern.

3.Develop the view function.

Page 34: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Creating a Django Template

We will introduce two constructs of django’s templating language:

1. A variable tag that is delimited by pairs of curly braces: {{ … }}.

A variable tag displays the contents of the object within the braces, which can be pure data or callables.

Inside a variable tag, you can use Python-style dot-notation to access attributes of the tag variables.

Page 35: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Creating a Django Template

2. A block tag that is delimited by curly braces and percent symbols : {% … %}.

A block tag is used to embed logic such as loops and conditions into a django html template.

Page 36: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

A Preliminary Template Created for presdebate Application

Page 37: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Creating a Django Template

Save the HTML template code shown in the previous slide into a directory called templates inside the application folder, which we need to create.

So the path to the template we just created is:

/users/xij6/django/jiangblog/presdebate/templates/mytemplate.html

Note that the name of the template is arbitrary, but the name of the templates directory is mandatory.

Page 38: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Creating a URL Pattern

The pathnames of an URL in a users’ browsers are mapped to various parts of an applicaton.

The IP address will be mapped to an Internet host (server), and the port number will be mapped to a port on the server.

Once the message arrives at the Internet host, the serve will match the remainder of the URL to the corresponding project. Then the remainder of the URL (with the project name excluded) will be passed to the project url configuration file.

Page 39: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Creating a URL Pattern

In our case in which we use a local host as the server, the type of request and the remainder of the URL (with the IP and port number excluded) will be passed to a django project URLconf (jiangblog/urls.py).

We therefore need to edit the URLconf so that when a valid pattern (regular expression) matches to the remainder of the URL received, the request will be further passed to the next receiver, which is the application URLconf we shell create later.

Page 40: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

jiangblog/urls.py before editing

Page 41: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

jiangblog/urls.py after editing

Page 42: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Creating a URL Pattern

The patterns() function takes as input a tuple (URL regular expression, destination).

The destination is either a view function that is called for URLs that match the pattern, or it’s a call to another URLconf file via include() function.

When include() is used, the current URL path head is removed and the remainder of the path is passed to the another URLconf file.

Page 43: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Creating a URL Pattern

For example, for http://localhost:8080/presdebate/xxx/yyy/zzz, the xxx/yyy/zzz will be passed to presdebate/urls.py as specified by include (“presdebate.urls”), by excluding the matching regex presdebate/

Page 44: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Creating a URL Pattern

The added line in the urlpattens entry of the project URLconf says that we are catching requests that begin with presdebate/ and passing them on to the presdebate/urls.py.

Recall that the presdebate does not contain a urls.py, thus we need to create this file from scratch.

Page 45: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

presdebate/urls.py

Page 46: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Creating a View Function-Create a Fake View First

The purpose of creating a fake view is to test quickly whether we’ve done so fast are correct.

To do this, we need to edit the jiangblog/presdebate/view.py file.

Page 47: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

jiangblog/presdebate/view.py before editing

Page 48: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

jiangblog/presdebate/view.py after editing

Page 49: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 50: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 51: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Creating Our Real View Function

Now we will create a view function that will fetch all of the comments stored in the database (mydb.db)and display them to users via our template.

Page 52: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

jiangblog/presdebate/view.py after editing

Page 53: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Creating Our Real View Function

If there is no records in mydb.db, we will receive an error. Thus, we need to initialize the mydb.db.

This can be done in several ways. One way is to add a review function in the view.py file called initializingdb()

Page 54: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

jiangblog/presdebate/view.py after editing

Page 55: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 56: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Working with User Input

Major Steps:

1.Adding an HTML form to our template.

2.Editing the application URLconf.

3.Adding a new view function that processes user input.

Page 57: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Adding an HTML Form to Our Template.

Page 58: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Adding an HTML Form to Our Template.

Page 59: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Cross-Site Request Forgery

Django comes with a data-preserving feature that disallows POSTs which are not secure against cross-site request forgery (CSRF) attacks.

You can read more about CSRF at the following website:

https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

Page 60: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Cross-Site Request Forgery

For our simple application, two fixes:

1. Add a CSFR token ({% csrf_token %} to forms that POST back to your site

2. Send the request context instance to the token via the template.

Page 61: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Editing the Application URLconf.

Page 62: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Adding a New View Function that Processes User Input

Page 63: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 64: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Adding a New View Function that Processes User Input

Page 65: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Adding a New View Function that Processes User Input

Page 66: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 67: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Trying Out the Django Admin

Django provides a automatic back-end administration application, or Admin for short.

Why do we need the Admin?

1. Testing during the development stage, even before the UI has been developed.

2. Manage the site easily.

Page 68: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 69: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Steps to Set up the Admin for a Django Project

1. Update the settings.py. Note that the Admin is also an application.

2. Run syncdb.

3. Editing the project URLconf file.

4. Register the PresDebate model with Admin.

Page 70: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Update the settings.py

Page 71: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Run syncdb

Page 72: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Editing the Project URLconf File.

Page 73: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Editing the Project URLconf File.

Page 74: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Register the PresDebate Model with the Admin

We need to inform Django which models should show up for editing in the Admin screens.

To do this, we will create a file named as admin.py in the presdebate directory.

Page 75: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Admin.py

Page 76: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

This Time the Admin Worked!

Page 77: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 78: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 79: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 80: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 81: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 82: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

We can also Edit/Add Comments Using the Admin

Page 83: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 84: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Editing Admin.py to Fix the “Display Issue”

Page 85: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 86: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .

Using Python Shell with Django Application

1. Run ./manage.py shell

This will bring up Ipython, which can be downloaded at: http://ipython.org/download.html

2. Run ./manage.py shell --plain

This will bring up python.

Page 87: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 88: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 89: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 90: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 91: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 92: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .
Page 93: Web Frameworks: Django Department of Biomedical Informatics University of Pittsburgh School of Medicine .