Python/Django Training

Preview:

DESCRIPTION

Python, django training

Citation preview

PYTHON – DJANGO TRAINING BY: BKIT ATOM, Epsilon Mobile @ HCMC HCMUT Summer 2012

Main reference:

https://docs.djangoproject.com/en/1.4/

Contact: bkitatom@gmail.com

Instructors

• Nguyễn Đức Minh Khôi (nguyenducminhkhoi@gmail.com)

• Phạm Trần Xuân Minh (clapika2010@gmail.com)

• Võ Xuân Thịnh (voxuanthinh24492@gmail.com)

• Trần Đăng Khoa (khoatran@epsilon-mobile.com)

• Lê Trung Hiếu (letrunghieu.cse09@gmail.com)

23/08/2012 Python - Django Training Course 2012 @HCMUT 2

Tools - set up

• This training using:

• notepad++ as the main development tool

• command line as the main environment

• Chrome/Firefox with firebug plugin browser

• Notice:

• In some setups you have to set some environment variables, to do this, in windows 7, press: Start > type: env > choose: edit the system environment variable > press: Environment variables button > system variable > choose path fields > add the path to the bin of required soft > press OK OR you just use cmd line: set PATH=path/to/your/bin;

• Some plugin in notepad++: Explorer, Light Explorer, Xbrackets Lite, TextFx, NppExec

23/08/2012 Python - Django Training Course 2012 @HCMUT 3

Contents

23/08/2012 Python - Django Training Course 2012 @HCMUT 4

Part 1: Introduction to Python/Django

Part 2: HTML + CSS + JavaScript

Part 3: Installation & Configuration

Part 4: Models

Part 5: QuerySets

Part 6: Admin Sites

Part 7: URL Configuration and Request/Response (Views)

Part 8: Software development support

Part 9: Django Templates

Part 10: Forms

Part 11: File Uploads and Generic View

Part 12: Other topics

Part 13: Deployment

Introduction to Python/Django - refs

• (1) You can refer to this slides: http://www.mediafire.com/?38s8z3989mh7buj

• (2) Python Basic Concepts slides: https://dl.dropbox.com/u/55056797/Training%20python.pdf

• (3) Or Visit this page for official document from Python.org: http://docs.python.org/archives/python-

2.7.3-docs-pdf-letter.zip

• (4) Python Style Guide: http://www.python.org/dev/peps/pep-0008/

• (5) For more information, visit this book: http://www.djangobook.com/en/2.0/

23/08/2012 Python - Django Training Course 2012 @HCMUT 5

Introduction to Python/Django

• Outcomes:

• Understand our course‟s outline

• Know the use of Python/Django in today‟s world

• Know some basic concept about python programming language (Built in types, statements, Class, Exception Handling,...)

• Can write some simple python program

23/08/2012 Python - Django Training Course 2012 @HCMUT 6

Overall Python/Django Course

• Section 1: Getting familiar with Python/Django • Part 1: Introduction to Python/Django • Part 2: HTML + CSS + JavaScript • Part 3: Installation & Configuration • Part 8: Software development support

• Section 2: Understanding Basics Parts: • Part 4: Models • Part 5: QuerySets • Part 7: URL Configuration and Request/Response (Views) • Part 9: Django Templates

• Section 3: Adding functions to your page: • Part 6: Admin Sites • Part 10: Forms • Part 11: File Uploads and Generic View • Part 12: Other topics • Part 13: Deployment

23/08/2012 Python - Django Training Course 2012 @HCMUT 7

Intro - Python Philosophy

• Beautiful is better than ugly.

• Explicit is better than implicit.

• Simple is better than complex.

• Complex is better than complicated.

• Flat is better than nested.

• Sparse is better than dense.

• Readability counts.

• Special cases aren't special enough to break the rules.

• Although practicality beats purity.

23/08/2012 Python - Django Training Course 2012 @HCMUT 8

Intro - Python Philosophy (cont.)

• Errors should never pass silently.

• Unless explicitly silenced.

• In the face of ambiguity, refuse the temptation to guess.

• There should be one-- and preferably only one --obvious way to do it.

• Although that way may not be obvious at first unless you're Dutch.

• Now is better than never.

• Although never is often better than right now.

• If the implementation is hard to explain, it's a bad idea.

• If the implementation is easy to explain, it may be a good idea.

• Namespaces are one honking great idea -- let's do more of those!

23/08/2012 Python - Django Training Course 2012 @HCMUT 9

Web components

23/08/2012 Python - Django Training Course 2012 @HCMUT 10

Web Dev. Levels

23/08/2012 Python - Django Training Course 2012 @HCMUT 11

Intro - Django Philosophy

• Loose coupling

• Less code

• Quick development

• Don‟t repeat yourself (DRY)

• Explicit is better than Implicit

• Consistency

• For more, use this document use guide: http://media.readthedocs.org/pdf/django/1.4.X/django.pdf

23/08/2012 Python - Django Training Course 2012 @HCMUT 12

Intro – Python Exercise

1. Write a program that continually reads integer numbers from the users until the user inputs value 0. After that, print out the average value of input numbers.

2. Write a guess number game. Each launching, the program will generate a random lucky number from 1 to 100. After that, the program will ask the user for a guess number. If the guess number is greater than the lucky number, it will print out “Too high”; if the guess number is less than the lucky number, it will print out “Too low”. The program will continue to ask a new guess number until the user enters the lucky number. As a consequence, it will print out “You guess right! It costs you x guesses”, where x is the number of guesses the user tries.

23/08/2012 Python - Django Training Course 2012 @HCMUT 13

Intro – Python Exercise (cont.)

3. Write a dictionary program (use Dictionary type). When launching, the users can choose 3 options from the main menu:

a. Search a word

b. Import dictionary

c. Exit

- If the user chooses Search a word, it will require him to enter a word, then, it will print out the definition of this word and return the main menu.

- If the user chooses Import dictionary, it will require him to enter the path of dictionary file. After that, it will import words and definitions in the file into the program dictionary. Finally, it returns the main menu.

- If the user chooses Exit, the program will terminate immediately. The dictionary file is a plain text file with the following format:

23/08/2012 Python - Django Training Course 2012 @HCMUT 14

Intro – Python Exercise (cont.)

4. Write a student management program (use Class). A student has 5 fields of information: ID, Name, Class, DOB (Date of Birth), GPA (Grade Point Average). The program will have 4 options from the main menu:

a. Explore all students

b. Add new student

c. Remove a student

d. Exit

- Explore all students: prints out all students with their information.

- Add new student: requires the user to enter the information for new student.

- Remove a student: removes a student by ID.

- Exit: terminates the program.

23/08/2012 Python - Django Training Course 2012 @HCMUT 15

Contents

23/08/2012 Python - Django Training Course 2012 @HCMUT 16

Part 1: Introduction to Python/Django

Part 2: HTML + CSS + JavaScript

Part 3: Installation & Configuration

Part 4: Models

Part 5: QuerySets

Part 6: Admin Sites

Part 7: URL Configuration and Request/Response (Views)

Part 8: Software development support

Part 9: Django Templates

Part 10: Forms

Part 11: File Uploads and Generic View

Part 12: Other topics

Part 13: Deployment

HTML + CSS + JavaScript

• Know some basic concepts about Web infrastructure

• Clearly know about some HTML tags and their functions

• Know some basic CSS attributes and their use

• Know some basic JS statements and clearly know some jQuery statements

• Write a basic form using jQuery/JS to manipulate the information

23/08/2012 Python - Django Training Course 2012 @HCMUT 18

Exercise

• Write HTML code to make this form

• Add CSS to make align and other styles if you want

• Write JS to check some input fields like this form. If any input fields is wrong, write the alert notice right after

that fields.

23/08/2012 Python - Django Training Course 2012 @HCMUT 19

Contents

23/08/2012 Python - Django Training Course 2012 @HCMUT 20

Part 1: Introduction to Python/Django

Part 2: HTML + CSS + JavaScript

Part 3: Installation & Configuration

Part 4: Models

Part 5: QuerySets

Part 6: Admin Sites

Part 7: URL Configuration and Request/Response (Views)

Part 8: Software development support

Part 9: Django Templates

Part 10: Forms

Part 11: File Uploads and Generic View

Part 12: Other topics

Part 13: Deployment

Installation & Configuration

• You can refer to this documents: http://www.mediafire.com/view/?dwo2133fcpvct16

• Remember to download and install the latest version of the software and tools

• For complete setup, please refer to this site: http://nguyenducminhkhoi.blogspot.com/2011/12/how-to-set-up-environment-for.html

• For complete option of settings.py, refer to this site: https://docs.djangoproject.com/en/1.4/ref/settings/

23/08/2012 Python - Django Training Course 2012 @HCMUT 21

Installation & Configuration - Outcomes

• Setup successfully according to the guides

• Understand Django Structure Directories and functions.

23/08/2012 Python - Django Training Course 2012 @HCMUT 22

Exercise

• Complete your own configure and projects.

• Write Hello World project to test your work!

23/08/2012 Python - Django Training Course 2012 @HCMUT 23

Contents

23/08/2012 Python - Django Training Course 2012 @HCMUT 24

Part 1: Introduction to Python/Django

Part 2: HTML + CSS + JavaScript

Part 3: Installation & Configuration

Part 4: Models

Part 5: QuerySets

Part 6: Admin Sites

Part 7: URL Configuration and Request/Response (Views)

Part 8: Software development support

Part 9: Django Templates

Part 10: Forms

Part 11: File Uploads and Generic View

Part 12: Other topics

Part 13: Deployment

Models - References

• (1) Django Models syntax: https://docs.djangoproject.com/en/1.4/topics/db/models/

• (2) Django Models Fields Type https://docs.djangoproject.com/en/1.4/ref/models/fields/

• (3) SQL Wikipedia reference: http://en.wikipedia.org/wiki/SQL

23/08/2012 Python - Django Training Course 2012 @HCMUT 25

Models - Outcomes

• Understand MVP, MVC Pattern Design

• Understand Django‟s infrastructure

• Know how to mapping a given design database to Django models

• Understand SQL Statements (DML, DDL, Queries)

• Use python manage.py syncdb to sync with database.

23/08/2012 Python - Django Training Course 2012 @HCMUT 26

MVP Design Pattern

• Django Framework based on MVP Design Pattern

• Model in Django is Model holding database of your website

• View in Django is Template or HTML, that shows your website interface

• Presenter in Django is Views, that control the flow and logic of your website

• So MVP design pattern in Django is MTV

23/08/2012 Python - Django Training Course 2012 @HCMUT 27

How things in Django works?

23/08/2012 Python - Django Training Course 2012 @HCMUT 28

Models

• Model:

• Is the single, definitive source of data about your data.

• Contains the essential fields and behaviors of the data you‟re storing.

• Each model maps to a single database table.

• Example:

• The above Person model would create a database table like this:

23/08/2012 Python - Django Training Course 2012 @HCMUT 29

Models (cont.)

• Review SQL Statements: • DDL (Data Definition Language)

• Query Statements: SELECT columnName,...

FROM tableName,...

WHERE expression

GROUP BY expression

HAVING expression

ORDER BY columnName

23/08/2012 Python - Django Training Course 2012 @HCMUT 30

Models (cont.)

• Review SQL Statements:

• DML (Data Manipulation Language)

23/08/2012 Python - Django Training Course 2012 @HCMUT 31

Models (cont.)

• Field types • The database column type (e.g. INTEGER, VARCHAR).

• The widget to use in Django's admin interface, if you care to use it (e.g. <input type="text">,<select>).

• The minimal validation requirements, used in Django's admin and in automatically-generated forms.

23/08/2012 Python - Django Training Course 2012 @HCMUT 32

Models (cont.)

• Field options

• Each field takes a certain set of field-specific arguments (documented in the model field reference). For example, CharField (and its subclasses) require a max_length argument which specifies the size of the VARCHAR database field used to store the data.

• Examples: null, blank, choices, default, primary_key, unique

• Verbose field names

23/08/2012 Python - Django Training Course 2012 @HCMUT 33

Models (cont.)

• Relationship:

• Many-to-one:

• use django.db.models.ForeignKey.

• requires a positional argument: the class to which the model is related.

• Many-to-many:

• use ManyToManyField.

• requires a positional argument: the class to which the model is related.

23/08/2012 Python - Django Training Course 2012 @HCMUT 34

Models (cont.)

23/08/2012 Python - Django Training Course 2012 @HCMUT 35

Can have recursive relationship

Models (cont.)

• One to one: • use OneToOneField

• primary key of an object when that object "extends" another object in some way.

• requires a positional argument: the class to which the model is related.

• Models across files:

23/08/2012 Python - Django Training Course 2012 @HCMUT 36

Models (cont.) • Model methods

• Sample method should define: • __unicode__(): returns a unicode "representation" of any object.

• get_absolute_url(): This tells Django how to calculate the URL for an object.

23/08/2012 Python - Django Training Course 2012 @HCMUT 37

Models (cont.)

• Override predefined method:

• Notice: • call the superclass method -- that's that super(Blog, self).save(*args,

**kwargs) business -- to ensure that the object still gets saved into the database.

• pass through the arguments that can be passed to the model method -- that's what the *args, **kwargs bit does. Django will, from time to time, extend the capabilities of built-in model methods, adding new arguments.

23/08/2012 Python - Django Training Course 2012 @HCMUT 38

Models (cont.) • Model fields:

23/08/2012 Python - Django Training Course 2012 @HCMUT 39

Please refer to: https://docs.djangoproject.com/en/1.4/ref/models/fields/ for more details

Models (cont.) - Homework • Write models.py files for the following database:

• Remember that, this exercise will be used through our homework exercises in our course, so keep in mind this models!

23/08/2012 Python - Django Training Course 2012 @HCMUT 40

23/08/2012 Python - Django Training Course 2012 @HCMUT 41

Contents

Part 1: Introduction to Python/Django

Part 2: HTML + CSS + JavaScript

Part 3: Installation & Configuration

Part 4: Models

Part 5: QuerySets

Part 6: Admin Sites

Part 7: URL Configuration and Request/Response (Views)

Part 8: Software development support

Part 9: Django Templates

Part 10: Forms

Part 11: File Uploads and Generic View

Part 12: Other topics

Part 13: Deployment

QuerySet – references

• (1) Making queries https://docs.djangoproject.com/en/1.4/topics/db/queries/

• (2) QuerySet API reference: https://docs.djangoproject.com/en/1.4/ref/models/querysets/

• (3) Database and project for this section is on: http://www.mediafire.com/?djd76f6uc3ieog5

23/08/2012 Python - Django Training Course 2012 @HCMUT 42

QuerySet – Outcome

• Make sure after this training, you understand:

23/08/2012 Python - Django Training Course 2012 @HCMUT 43

QuerySet API

23/08/2012 Python - Django Training Course 2012 @HCMUT 44

QuerySet API

23/08/2012 Python - Django Training Course 2012 @HCMUT 45

QuerySet –Example1 • We will have 3 model:

#without inheritance from models.Model class

class Student():

id_student = models.IntegerField()

email = models.EmailField()

#without using def __unicode__(self):

class Student2(models.Model):

id_student = models.IntegerField()

email = models.EmailField()

#and class student3 with inheritance and __unicode__ function

class Student3(models.Model):

name = models.CharField(max_length=200)

email = models.EmailField()

def __unicode__(self):

return 'name: %s and email %s ' % (self.name , self.email)

23/08/2012 Python - Django Training Course 2012 @HCMUT 46

QuerySet-Using python shell

23/08/2012 Python - Django Training Course 2012 @HCMUT 47

Let‟s start create some objects!!!

QuerySet-Exercises1:

23/08/2012 Python - Django Training Course 2012 @HCMUT 48

Using Student3 model, create 35 students who has name is in form: one lowercase letter and its uppercase, email in form “[name]@mysite.com” For example:

QuerySet- with relations Gender_choise = (('m','Male'),('f','Female'))

class Article(models.Model):

name = models.CharField(max_length=200)

gender = models.CharField(max_length=1 ,choices=Gender_choise)

def __unicode__(self):

return "article: %s" %self.name

class Song(models.Model):

name = models.CharField(max_length=200)

article = models.ForeignKey(to=Article,related_name='composed')

def __unicode__(self):

return "song: %s" %self.name

class Playlist(models.Model):

name = models.CharField(max_length=200)

listmusic = models.ManyToManyField(to=Song,related_name='of_playlist')

def __unicode__(self):

return "playlist %s" %self.name

23/08/2012 Python - Django Training Course 2012 @HCMUT 49

QuerySet-wit relations(2)

23/08/2012 Python - Django Training Course 2012 @HCMUT 50

QuerySet-with relations (3)

23/08/2012 Python - Django Training Course 2012 @HCMUT 51

QuerySet- exercises class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) website = models.URLField(blank= True,null=True) def __unicode__(self): return self.name Gender_choise = (('m','Male'),('f','Female')) class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() gender = models.CharField(max_length=1,choices=Gender_choise) def __unicode__(self): return "%s %s" %(self.first_name,self.last_name) class Book(models.Model): title= models.CharField(max_length=100) author = models.ManyToManyField(to=Author,related_name="writed") publisher = models.ForeignKey(to=Publisher,related_name="published") publication_date = models.DateField(blank= True,null=True) def __unicode__(self): return self.title

23/08/2012 Python - Django Training Course 2012 @HCMUT 52

QuerySet – Class exercise

• Print Author‟s name (in order from z to a) and his (her) books.

• Print all Author, who use yahoo mail. (the difference from get and filter)

• Print book that has publisher address is USA

• Print all books that has publisher before 1/1/2012.

• Print books that has been written by women writers.

• Confirm that we already has book that‟s name “Steve Jobs” if not create one.

• Confirm that we already has book that‟s name “Bill Gates” if not create one.

23/08/2012 Python - Django Training Course 2012 @HCMUT 53

QuerySet – Homework Exercise

• Use the database you designed last week to complete these questions

- Create an app with those models.

- Use shell to complete the following:

• CREATING

+ Create 100 EMPLOYEEs

+ Create 20 PROJECTs

+ Create DEPARTMENTs: HR, IT, marketing, R & D,

23/08/2012 Python - Django Training Course 2012 @HCMUT 54

QuerySet – Homework Exercise

• RETRIEVING

+ Filter all employees work for HR department

+ Filter all employees work on projects control by IT department

+ Filter all employees that is a supervisor of some other employees

+ Filter all departments that manages by employees that work for project with specific id( you can choose whatever id you want)

• DELETING

+ Delete a given employee with name

+ Delete all Psychology movies

Note: please capture your screens when doing those steps and add them to your report (doc or pdf file).

23/08/2012 Python - Django Training Course 2012 @HCMUT 55

Contents

23/08/2012 Python - Django Training Course 2012 @HCMUT 56

Part 1: Introduction to Python/Django

Part 2: HTML + CSS + JavaScript

Part 3: Installation & Configuration

Part 4: Models

Part 5: QuerySets

Part 6: Admin Sites

Part 7: URL Configuration and Request/Response (Views)

Part 8: Software development support

Part 9: Django Templates

Part 10: Forms

Part 11: File Uploads and Generic View

Part 12: Other topics

Part 13: Deployment

Admin sites (cont.) – reference

• (1) For complete tutorial on setup and running admin sites, visit: https://docs.djangoproject.com/en/1.4/intro/tutorial02/

• (2) For complete document about Django Admin Sites, visit: https://docs.djangoproject.com/en/1.4/ref/contrib/admin/

• (3) And: https://docs.djangoproject.com/en/1.4/ref/contrib/admin/actions/

23/08/2012 Python - Django Training Course 2012 @HCMUT 57

Admin sites (cont.) - outcomes

• Know how to set up for admin sites

• ModelAdmin Object

• ModelAdmin Option

• ModelAdmin Action

• ModelAdmin Method

• InlineModelAdmin Object

• InlineModelAdmin Option

• Overriding Admin Templates (Optional)

• Adding Custom Validation to admin (Optional)

23/08/2012 Python - Django Training Course 2012 @HCMUT 58

Admin sites

• “One of the most powerful parts of Django. It reads metadata in your model to provide a powerful and production-ready interface

that content producers can immediately use to start adding content to the site.”

23/08/2012 Python - Django Training Course 2012 @HCMUT 59

Admin sites (cont.) – setup • How to activate the admin sites mode:

1. Add 'django.contrib.admin' to your INSTALLED_APPS setting.

2. The admin has four dependencies - django.contrib.auth, django.contrib.contenttypes,django.contrib.messages and django.contrib.sessions. If these applications are not in your INSTALLED_APPS list, add them.

3. Add django.contrib.messages.context_processors.messages to TEMPLATE_CONTEXT_PROCESSORS andMessageMiddleware to MIDDLEWARE_CLASSES. (These are both active by default, so you only need to do this if you’ve manually tweaked the settings.)

4. Determine which of your application’s models should be editable in the admin interface.

5. For each of those models, optionally create a ModelAdmin class that encapsulates the customized admin functionality and options for that particular model.

6. Instantiate an AdminSite and tell it about each of your models and ModelAdmin classes.

7. Hook the AdminSite instance into your URLconf.

• visiting the URL you hooked it into (/admin/, by default).

23/08/2012 Python - Django Training Course 2012 @HCMUT 60

Admin sites (cont.) – ModelAdmin

• The ModelAdmin class is the representation of a model in the admin interface.

• These are stored in a file named admin.py in your application

• If you are happy with the default admin interface, just use:

23/08/2012 Python - Django Training Course 2012 @HCMUT 61

Admin sites (cont.) – ModelAdmin Options

• ModelAdmin.actions_on_top

• ModelAdmin.actions_on_bottom

• ModelAdmin.actions_selection_counter

• ModelAdmin.date_hierarchy

23/08/2012 Python - Django Training Course 2012 @HCMUT 62

Admin sites (cont.) – ModelAdmin Actions

23/08/2012 Python - Django Training Course 2012 @HCMUT 63

Admin sites (cont.) – ModelAdmin

• ModelAdmin.exclude

• ModelAdmin.fields

23/08/2012 Python - Django Training Course 2012 @HCMUT 64

Admin sites (cont.) – ModelAdmin

• ModelAdmin.fieldsets

23/08/2012 Python - Django Training Course 2012 @HCMUT 65

Admin sites (cont.) – ModelAdmin • ModelAdmin.list_display

23/08/2012 Python - Django Training Course 2012 @HCMUT 66

ModelAdmin.list_display_links ModelAdmin.list_editable

Admin sites (cont.) – ModelAdmin • ModelAdmin.list_filter

• ModelAdmin.search_fields

23/08/2012 Python - Django Training Course 2012 @HCMUT 67

Admin sites (cont.) – ModelAdmin

• ModelAdmin.list_max_show_all

• ModelAdmin.list_per_page

• ModelAdmin.list_select_related

• ModelAdmin.ordering

• ModelAdmin.paginator

• ModelAdmin.save_as

23/08/2012 Python - Django Training Course 2012 @HCMUT 68

Admin sites (cont.) – InlineModelAdmin

• TabularInline

• StackedInline

• You can edit the books authored by an author on the author page. You add inlines to a model by specifying them in a ModelAdmin.inlines:

• Some InlineModelAdmin options

23/08/2012 Python - Django Training Course 2012 @HCMUT 69

Admin sites (cont.)

• Overriding admin templates, see more at documents!

23/08/2012 Python - Django Training Course 2012 @HCMUT 70

Admin sites (cont.) - Homework

Admin page

+ Add all of the models above to admin site.

+ Manage projects of a department by StackInline

+ Manage department managed by an employee by TabularInline

+ Add all below actions to admin page:

- Filter all employees with odd id

- Filter all employees with total timework is more than 40 hours

- Filter all projects which total salary of worker is more than 500usd

23/08/2012 Python - Django Training Course 2012 @HCMUT 71

23/08/2012 Python - Django Training Course 2012 @HCMUT 72

Contents

Part 1: Introduction to Python/Django

Part 2: HTML + CSS + JavaScript

Part 3: Installation & Configuration

Part 4: Models

Part 5: QuerySets

Part 6: Admin Sites

Part 7: URL Configuration and Request/Response (Views)

Part 8: Software development support

Part 9: Django Templates

Part 10: Forms

Part 11: File Uploads and Generic View

Part 12: Other topics

Part 13: Deployment

URLs & Views - reference

• (1) Python regular expression http://docs.python.org/library/re.html#regular-expression-syntax

• (2) URL Dispatcher https://docs.djangoproject.com/en/1.4/topics/http/urls/

• (3) Writing Views: https://docs.djangoproject.com/en/dev/topics/http/views/

• (4) Request and response objects https://docs.djangoproject.com/en/1.4/ref/request-response/

• (5) Render [to response] function: https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render-to-response

23/08/2012 Python - Django Training Course 2012 @HCMUT 73

URLs & Views - Outcomes

• Understand some basics python regular expression

• Clearly understand the URL Dispatcher‟s working

• Apply some Request and response objects to simple views and generate a simple website

23/08/2012 Python - Django Training Course 2012 @HCMUT 74

How things in Django works?

23/08/2012 Python - Django Training Course 2012 @HCMUT 75

Regular Expressions (RE)

• “A regular expression (or RE) specifies a set of strings that matches it; the functions in this module let you check if a particular string matches a given regular expression”

• Regular expressions can be concatenated to form new regular expressions

• If A and B are both regular expressions, then AB is also a regular expression.

• In general, if a string p matches A and another string q matches B, the string pq will match AB

23/08/2012 Python - Django Training Course 2012 @HCMUT 76

Some useful REs in Python

• Special characters: „.‟ , „^‟, „$‟, „*‟, „+‟, „?‟, „\‟ , „|‟

• Brackets: {m}, {m, n}, [ab], [0-9], (ab)

• Others: (?P<name>...), \d, \s

• For more information about meanings of above symbols, visit (1)

23/08/2012 Python - Django Training Course 2012 @HCMUT 77

How to use RE in python

• regular expressions use the backslash character ('\') to indicate special forms or to allow special characters to be used without invoking their special meaning

• string literal prefixed with 'r'

23/08/2012 Python - Django Training Course 2012 @HCMUT 78

How to use RE in python

23/08/2012 Python - Django Training Course 2012 @HCMUT 79

URL Dispatcher

• To design URLs for an app, you create a Python module informally called a URLconf (URL configuration).

• This module is pure Python code and is a simple mapping between URL patterns (as simple regular expressions) to Python callback functions (your views).

• Use in urls.py in project and app folder

23/08/2012 Python - Django Training Course 2012 @HCMUT 80

URL – sample requests explain

• A request to /articles/2005/03/ would match the third entry in the list. Django would call the function news.views.month_archive(request, '2005', '03').

• /articles/2005/3/ would not match any URL patterns, because the third entry in the list requires two digits for the month.

• /articles/2003/ would match the first pattern in the list, not the second one, because the patterns are tested in order, and the first one is the first test to pass. Feel free to exploit the ordering to insert special cases like this.

• /articles/2003 would not match any of these patterns, because each pattern requires that the URL end with a slash.

• /articles/2003/03/03/ would match the final pattern. Django would call the function news.views.article_detail(request, '2003', '03', '03').

23/08/2012 Python - Django Training Course 2012 @HCMUT 81

URL – non-named/named groups

• non-named regular-expression groups (via parenthesis) to capture bits of the URL and pass them as positional arguments to a view.

• named regular-expression groups to capture URL bits and pass them as keyword arguments to a view.

• the syntax for named regular-expression groups is (?P<name>pattern), where name is the name of the group and pattern is some pattern to match.

• If there are any named arguments, it will use those, ignoring non-named arguments. Otherwise, it will pass all non-named arguments as positional arguments.

23/08/2012 Python - Django Training Course 2012 @HCMUT 82

URL – non-named/named groups

23/08/2012 Python - Django Training Course 2012 @HCMUT 83

URL - utility functions

• django.conf.urls utility functions:

• patterns(prefix, pattern_description, ...)

• url(regex, view, kwargs=None, name=None, prefix='')

• include(<module or pattern_list>)

23/08/2012 Python - Django Training Course 2012 @HCMUT 84

URL – view prefix

23/08/2012 Python - Django Training Course 2012 @HCMUT 85

URL - Passing extra options to view functions

• In views.py, we have callback function: year_archive(request, year, foo)

23/08/2012 Python - Django Training Course 2012 @HCMUT 86

Writing views

• View is simply a Python function that takes a Web request and returns a Web response

• This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really.

• The view itself contains whatever arbitrary logic is necessary to return that response.

23/08/2012 Python - Django Training Course 2012 @HCMUT 87

Request/ Response

• Django uses request and response objects to pass state through the system.

• HttpRequest objects: • HttpRequest.body

• HttpRequest.path

• HttpRequest.path_info

• HttpRequest.method

• HttpRequest.GET

• HttpRequest.POST

• HttpRequest.FILES

• HttpRequest.META

• HttpRequest.user

• Read more at (4)

23/08/2012 Python - Django Training Course 2012 @HCMUT 88

Request/ Response (cont.)

• UploadedFile objects

• UploadedFile.name

• UploadedFile.size

• UploadedFile.chunks(chunk_size=None)

• UploadedFile.read(num_bytes=None)

• HttpResponse objects

• In contrast to HttpRequest objects, which are created automatically by Django, HttpResponse objects are your responsibility. Each view you write is responsible for instantiating, populating and returning an HttpResponse.

23/08/2012 Python - Django Training Course 2012 @HCMUT 89

Request/ Response (cont.)

• Usage:

• HttpResponse subclasses

• class HttpResponseRedirect

• class HttpResponseBadRequest (400)

• class HttpResponseNotFound (404)

• class HttpResponseForbidden (403)

• class HttpResponseServerError (500)

23/08/2012 Python - Django Training Course 2012 @HCMUT 90

• render(request, template_name[, dictionary][,

context_instance][, content_type][, status][, current_app])

• Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text.

Django shortcut functions

23/08/2012 Python - Django Training Course 2012 @HCMUT 91

Django shortcut functions (cont.) • render_to_response(template_name[, dictionary][,

context_instance][, mimetype]) • Renders a given template with a given context dictionary and returns

an HttpResponse object with that rendered text.

23/08/2012 Python - Django Training Course 2012 @HCMUT 92

Django shortcut functions (cont.)

• redirect(to[, permanent=False], *args, **kwargs):

• Returns an HttpResponseRedirect to the appropriate URL for the arguments passed.

23/08/2012 Python - Django Training Course 2012 @HCMUT 93

Django shortcut functions (cont.)

23/08/2012 Python - Django Training Course 2012 @HCMUT 94

Homework

• Write urls.py to map with the following views:

• /employee/?P<e_id> -> employee(id)

• /Department/?P<d_name> -> department()

• /Project/?P<p_name> -> project()

• End in your view, you should implement the exercise in Part 5: QuerySets about employee, department, and project, using render_to_response() function.

23/08/2012 Python - Django Training Course 2012 @HCMUT 95

Contents

23/08/2012 Python - Django Training Course 2012 @HCMUT 96

Part 1: Introduction to Python/Django

Part 2: HTML + CSS + JavaScript

Part 3: Installation & Configuration

Part 4: Models

Part 5: QuerySets

Part 6: Admin Sites

Part 7: URL Configuration and Request/Response (Views)

Part 8: Software development support

Part 9: Django Templates

Part 10: Forms

Part 11: File Uploads and Generic View

Part 12: Other topics

Part 13: Deployment

Dev. Tools - references

• (1) Please refer to this document: http://www.mediafire.com/view/?x074zrdwd40g4u7

23/08/2012 Python - Django Training Course 2012 @HCMUT 97

Dev. tools - outcomes

• An overview of Software Development Process

• Subversion - Working remotely with team (SVN)

• Project Management Systems (Teamlab)

• Bugs Tracker (Trello)

23/08/2012 Python - Django Training Course 2012 @HCMUT 98

Software dev. tools Exercise

• You should you at least SVN in your Final Project when working with your partner.

23/08/2012 Python - Django Training Course 2012 @HCMUT 99

23/08/2012 Python - Django Training Course 2012 @HCMUT 100

Contents

Part 1: Introduction to Python/Django

Part 2: HTML + CSS + JavaScript

Part 3: Installation & Configuration

Part 4: Models

Part 5: QuerySets

Part 6: Admin Sites

Part 7: URL Configuration and Request/Response (Views)

Part 8: Software development support

Part 9: Django Templates

Part 10: Forms

Part 11: File Uploads and Generic View

Part 12: Other topics

Part 13: Deployment

Django Templates - reference

• (1) Django template language: https://docs.djangoproject.com/en/1.4/topics/templates/

• (2) Built-in template tags and filters: https://docs.djangoproject.com/en/1.4/ref/templates/builtins/

• (3) If you want to look more technical part, read this: https://docs.djangoproject.com/en/1.4/ref/templates/api/

23/08/2012 Python - Django Training Course 2012 @HCMUT 101

Django Templates - outcomes

• Understand some basics concepts about django templates and simple HTML view

• Introduce a simple views.py

• Write some code that combines django template and simple view

23/08/2012 Python - Django Training Course 2012 @HCMUT 102

Templates

• A template is simply a text file

• A template contains:

• Variables: get replaced with values

• Tags: control the logic of the template

23/08/2012 Python - Django Training Course 2012 @HCMUT 103

• Syntax: {{ variable }}

i = 1, j = 2

class book(models.Model):

title = models.CharField(max_length=50)

author = models.CharField(max_length=35)

obj = book(title = “My life”, author = “Unknow”)

obj can be a non-parametric function

23/08/2012 Python - Django Training Course 2012 @HCMUT 104

Variable

<p> This is line {{ i }}</p> <p> This is line {{ j }}</p>

<p> This is line 1</p> <p> This is line 3</p>

<h3> {{ obj.title }} </h3> <p> {{ obj.author }} </p>

<h3> My life </h3> <p> Unknow </p>

Tags

• Syntax:

• {% tag %}

• {% tag %} ... tag contents ... {% endtag %}

list = [1, 2, 3, 4] display: List: 1 2 3 4

list = [] display: List is empty

• {# This is a comment #}

23/08/2012 Python - Django Training Course 2012 @HCMUT 106

{% if list | length > 0 %} List: {% for i in list %} {{ i }} {% endfor %} {% else %} List is empty {% endif %}

Tags: inheritance

• base.html

• template.html

23/08/2012 Python - Django Training Course 2012 @HCMUT 107

<p>This is a example</p> <title>{% block title %}My site{% endblock %}</title> <div>{% block content %} {% endblock %}</div>

{% extends "base.html" %} {% block title %}Welcome !{% endblock %} {% block content %} <ul> {% for i in [1, 2] %} <li>This is line {{ i }}</li> {% endfor %} </ul> {% endblock %}

Tags: inheritance

• template.html

23/08/2012 Python - Django Training Course 2012 @HCMUT 108

<p>This is a example</p> <title>Welcome !</title> <div <ul> <li> This is line 1 </li> <li> This is line 2 </li> </ul> </div>

Escape

Example: {{ obj }}

obj = <b>Bold</b>

This will be escaped:

This will not be escaped:

Block autoescape

23/08/2012 Python - Django Training Course 2012 @HCMUT 109

<b>Bold</b>

Bold

{% autoescape on %} Example {{ obj }} {% endautoescape %}

{% autoescape off %} Example {{ obj }} {% endautoescape %}

Example <b>Bold</b> Example Bold

Loading templates

setting.py template.html

views.py

23/08/2012 Python - Django Training Course 2012 @HCMUT 110

TEMPLATE_DIR = ( “mysite/app/template”, “home/default”, )

def viewExample(request, title, author): obj = book(title, author) return render_to_response( “template.html”, {“book” : obj}, context_instance=RequestContext(request))

<p> This is a book </p> <p> Title: {{ book.title }} </p> <p> Author: {{ book.author }}</p>

<p> This is a book </p> <p> Title: My life </p> <p> Author: H.Anh </p>

Django Templates - Exercises

• Write Django Templates for these page:

• Search all employees according to given Name, SSN, Bdates (between X and Y)

23/08/2012 Python - Django Training Course 2012 @HCMUT 111

23/08/2012 Python - Django Training Course 2012 @HCMUT 112

Contents

Part 1: Introduction to Python/Django

Part 2: HTML + CSS + JavaScript

Part 3: Installation & Configuration

Part 4: Models

Part 5: QuerySets

Part 6: Admin Sites

Part 7: URL Configuration and Request/Response (Views)

Part 8: Software development support

Part 9: Django Templates

Part 10: Forms

Part 11: File Uploads and Generic View

Part 12: Other topics

Part 13: Deployment

Forms - references

• (1) Working with forms: https://docs.djangoproject.com/en/1.4/topics/forms/

• (2) Form API: https://docs.djangoproject.com/en/1.4/ref/forms/api/

• (3) FormFields Reference: https://docs.djangoproject.com/en/1.4/ref/forms/fields/

• (4) Form from models: https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/

23/08/2012 Python - Django Training Course 2012 @HCMUT 113

Forms - Outcomes

• Know how to create a simple form

• Understand how forms are generated and display form in the way you want

• Know how to generate form from a given model

• Know how to make a simple website using form

23/08/2012 Python - Django Training Course 2012 @HCMUT 114

Form Objects

• A Form object encapsulates a sequence of form fields and a collection of validation rules that must be fulfilled in order for the form to be accepted.

• An unbound form does not have any data associated with it; when rendered to the user, it will be empty or will contain default values.

• A bound form does have submitted data, and hence can be used to tell if that data is valid.

23/08/2012 Python - Django Training Course 2012 @HCMUT 115

Using Form in a view

• If the form has not been submitted, an unbound instance of ContactForm is

created and passed to the template.

• If the form has been submitted, a bound instance of the form is created using request.POST. If the submitted data is valid, it is processed and the user is re-directed to a "thanks" page.

• If the form has been submitted but is invalid, the bound form instance is passed on to the template.

23/08/2012 Python - Django Training Course 2012 @HCMUT 116

Processing the data from a form

• What is cleaned_data? • For example, DateField normalizes input into

Python datetime.date object. Regardless of whether you pass it a string in the format '1994-07-15', a datetime.date object, or a number of other formats,DateField will always normalize it to a datetime.date object as long as it's valid.

23/08/2012 Python - Django Training Course 2012 @HCMUT 117

Displaying a form using a template

• form.as_p, form.as_table, form.as_ul (list)

• Form.errors: Access the errors attribute to get a dictionary of error messages:

23/08/2012 Python - Django Training Course 2012 @HCMUT 118

Customizing the form template

23/08/2012 Python - Django Training Course 2012 @HCMUT 119

• {{ field.label }}

• {{ field.label_tag }}

• {{ field.value }}

• {{ field.html_name }}

• {{ field.help_text }}

• {{ field.errors }}

23/08/2012 Python - Django Training Course 2012 @HCMUT 120

Looping over the form's fields

Form fields – core fields argument

• required

• label:

23/08/2012 Python - Django Training Course 2012 @HCMUT 121

Form fields – core fields argument • initial:

• help_text:

• Error_messages:

23/08/2012 Python - Django Training Course 2012 @HCMUT 122

Form fields – built in fields classes • BooleanField

• CharField

• ChoiceField

• TypedChoiceField

• DateField

• DateTimeField

• DecimalField

• EmailField

• FileField

• FilePathField

• FloatField

• ImageField

23/08/2012 Python - Django Training Course 2012 @HCMUT 123

• IntegerField

• IPAddressField

• GenericIPAddressField

• MultipleChoiceField

• TypedMultipleChoiceField

• NullBooleanField

• RegexField

• SlugField

• TimeField

• URLField

ModelForms

• Make form directly from models

• Fields type conversion: see more at: https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/#field-types

23/08/2012 Python - Django Training Course 2012 @HCMUT 124

ModelForms • The save() method:

• creates and saves a database object from the data bound to the form.

• save() will raise a ValueError if the data in the form doesn't validate -- i.e., if form.errors evaluates to True.

• If you call save() with commit=False, then it will return an object that hasn't yet been saved to the database.

• you can invoke save_m2m() to save the many-to-many form data

23/08/2012 Python - Django Training Course 2012 @HCMUT 125

ModelForms – customize

• Overriding the default field types or widgets:

23/08/2012 Python - Django Training Course 2012 @HCMUT 126

Forms – Exercises

• Write 2 pages that have functions:

• Django Templates Exercise, when click on a name of an employee, this will link to the page of displaying details of this employee. At this page, you can edit the information and save to the database!, or at this page, if you want to delete this employee, you can press button delete. Be careful the integrity with other tables!.

• Creating new employee page and save to the database.

23/08/2012 Python - Django Training Course 2012 @HCMUT 127

23/08/2012 Python - Django Training Course 2012 @HCMUT 128

Contents

Part 1: Introduction to Python/Django

Part 2: HTML + CSS + JavaScript

Part 3: Installation & Configuration

Part 4: Models

Part 5: QuerySets

Part 6: Admin Sites

Part 7: URL Configuration and Request/Response (Views)

Part 8: Software development support

Part 9: Django Templates

Part 10: Forms

Part 11: File Uploads and Generic View

Part 12: Other topics

Part 13: Deployment

File Uploads and Generic View- reference • (1) File Uploads:

https://docs.djangoproject.com/en/1.4/topics/http/file-uploads/

• (2) Storage API: https://docs.djangoproject.com/en/1.4/ref/files/storage/

• (3) Managing Files: https://docs.djangoproject.com/en/1.4/topics/files/

• (4) Output PDF with Django: https://docs.djangoproject.com/en/1.4/howto/outputting-pdf/

• (5) Generic Views: https://docs.djangoproject.com/en/1.4/topics/class-based-views/ and: https://docs.djangoproject.com/en/1.4/ref/generic-views/

• (6) Built in Generic Views: https://docs.djangoproject.com/en/1.4/ref/class-based-views/

23/08/2012 Python - Django Training Course 2012 @HCMUT 129

File Uploads and Generic View - Outcomes

• Know how to work with file upload

• Understand how generic view works

• Write a simple program to deal with file upload and generic views

23/08/2012 Python - Django Training Course 2012 @HCMUT 130

File Uploads

• Conditions in templates to use:

• enctype="multipart/form-data“

• method was POST

23/08/2012 Python - Django Training Course 2012 @HCMUT 131

Handling uploaded files

• read()

• multiple_chunks()

• chunks()

• name

• size

• Changing upload handlers: in settings.py: • FILE_UPLOAD_MAX_MEMORY_SIZE

• FILE_UPLOAD_TEMP_DIR

• FILE_UPLOAD_PERMISSIONS

• FILE_UPLOAD_HANDLERS

23/08/2012 Python - Django Training Course 2012 @HCMUT 132

Storage class

• accessed_time(name)

• created_time(name)

• delete(name)

• exists(name)

• get_available_name(name)

• get_valid_name(name)

• listdir(path)

• modified_time(name)

• open(name, mode='rb')

• path(name)

• save(name, content)

• size(name)

• url(name)

23/08/2012 Python - Django Training Course 2012 @HCMUT 133

Outputting PDF • Install ReportLab:

• Write your view

23/08/2012 Python - Django Training Course 2012 @HCMUT 134

Generic Views

• Generic views:

• let you quickly provide common views of an object without actually needing to write any Python code.

• django.views.generic.simple • django.views.generic.simple.direct_to_template:

• django.views.generic.simple.redirect_to

23/08/2012 Python - Django Training Course 2012 @HCMUT 135

Generic Views (cont.) • Other Generic views:

• Date-based generic views

• django.views.generic.date_based.archive_index

• django.views.generic.date_based.archive_year

• django.views.generic.date_based.archive_month

• django.views.generic.date_based.archive_week

• django.views.generic.date_based.archive_day

• django.views.generic.date_based.archive_today

• django.views.generic.date_based.object_detail

• List/detail generic views

• django.views.generic.list_detail.object_list

• django.views.generic.list_detail.object_detail

• Create/update/delete generic views

• django.views.generic.create_update.create_object

• django.views.generic.create_update.update_object

• django.views.generic.create_update.delete_object

23/08/2012 Python - Django Training Course 2012 @HCMUT 136

Generic Views (cont.)

• list_detail.object_list e.g

23/08/2012 Python - Django Training Course 2012 @HCMUT 137

Generic Views (cont.)

• Other necessary fields:

23/08/2012 Python - Django Training Course 2012 @HCMUT 138

Generic Views (cont.)

• To build a list page of all publishers

• In the absence of an explicit template Django will infer one from the object's name. i.e. "books/publisher_list.html“

• Remember to enable in TEMPLATE_LOADERS in settings.py

23/08/2012 Python - Django Training Course 2012 @HCMUT 139

File Uploads and GV - Exercises

• In Edit and create new Employee, add or change avatar image Upload fields (remember to add fields in models.py)

• Write generic Views page for simple pages like: welcome page, Successful page,...

23/08/2012 Python - Django Training Course 2012 @HCMUT 141

23/08/2012 Python - Django Training Course 2012 @HCMUT 142

Contents

Part 1: Introduction to Python/Django

Part 2: HTML + CSS + JavaScript

Part 3: Installation & Configuration

Part 4: Models

Part 5: QuerySets

Part 6: Admin Sites

Part 7: URL Configuration and Request/Response (Views)

Part 8: Software development support

Part 9: Django Templates

Part 10: Forms

Part 11: File Uploads and Generic View

Part 12: Other topics

Part 13: Deployment

Other topics - references

• (1) User authentication in Django: https://docs.djangoproject.com/en/dev/topics/auth/

• (2) Testing Django Applications: https://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs

• (3) Sending Email: https://docs.djangoproject.com/en/dev/topics/email/

• (4) Pagination: https://docs.djangoproject.com/en/dev/topics/pagination/?from=olddocs

• (5) Turn off debug modes: http://djangobook.com/en/2.0/chapter12/

23/08/2012 Python - Django Training Course 2012 @HCMUT 143

Other topics - Outcomes

• Understand clearly and apply these information in your project, exercises.

23/08/2012 Python - Django Training Course 2012 @HCMUT 144

User authentication

• The auth system consists of:

• Users

• Permissions: Binary (yes/no) flags designating whether a user may perform a certain task.

• Groups: A generic way of applying labels and permissions to more than one user.

• Installation, in settings.py:

• Put 'django.contrib.auth' and 'django.contrib.contenttypes' in your INSTALLED_APPS setting.

• Run the command manage.py syncdb.

23/08/2012 Python - Django Training Course 2012 @HCMUT 145

User authentication (cont.) • Class models.User has fields:

• username

• first_name

• last_name

• email

• password

• is_staff

• is_active

• is_superuser

• last_login

• date_joined

• Class models.UserManager has helper functions: • create_user(username, email=None, password=None)

• make_random_password(length=10,allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')

23/08/2012 Python - Django Training Course 2012 @HCMUT 146

• Class models.User has methods:

• is_anonymous()

• is_authenticated()

• get_full_name()

• set_password()

• check_password(raw_password)

• get_all_permissions(obj=None)

• email_user(subject, message, from_email=None)

• get_profile()

User authentication (cont.)

• Usage:

• creating users:

• changing password:

• creating superuser:

23/08/2012 Python - Django Training Course 2012 @HCMUT 147

User authentication (cont.)

• Storing additional information about user:

• in modes.py:

User.profile = property(lambda u: PubProfile.objects.get_or_create(user=u)[0]) # (Tips)

• in settings.py:

23/08/2012 Python - Django Training Course 2012 @HCMUT 148

User authentication (cont.)

• How to log a user in: • Authenticate() and login():

• logout():

23/08/2012 Python - Django Training Course 2012 @HCMUT 149

User authentication (cont.)

• Limiting access – login_required decorator:

• decorators.login_required([redirect_field_name=REDIRECT_FIELD_NAME,login_url=None])

• redirect_field_name by default is = “next”

• login_url by defaults is = settings.LOGIN_URL (in settings.py)

• And map with views:

23/08/2012 Python - Django Training Course 2012 @HCMUT 150

User authentication (cont.) • Writing login page:

• manually if you want like any other templates, and views

• Built-in views, the usage is like Generic Views:

• login(request[, template_name, redirect_field_name, authentication_form])

• logout(request[, next_page, template_name, redirect_field_name])

• logout_then_login(request[, login_url])

• password_change(request[, template_name, post_change_redirect,password_change_form])

• password_change_done(request[, template_name])

• password_reset(request[, is_admin_site, template_name, email_template_name,password_reset_form, token_generator, post_reset_redirect, from_email])

• password_reset_done(request[, template_name])

• password_reset_confirm(request[, uidb36, token, template_name, token_generator,set_password_form, post_reset_redirect])

• password_reset_complete(request[, template_name])

• redirect_to_login(next[, login_url, redirect_field_name])

• See more at (1)

23/08/2012 Python - Django Training Course 2012 @HCMUT 151

User authentication (cont.)

• Built-in forms:

• class AdminPasswordChangeForm: A form used in the admin interface to change a user's password.

• class AuthenticationForm: A form for logging a user in.

• class PasswordChangeForm: A form for allowing a user to change their password.

• class PasswordResetForm: A form for generating and emailing a one-time use link to reset a user's password.

• class SetPasswordForm: A form that lets a user change his/her password without entering the old password.

• class UserChangeForm: A form used in the admin interface to change a user's information and permissions.

• class UserCreationForm: A form for creating a new user.

23/08/2012 Python - Django Training Course 2012 @HCMUT 152

Testing Django App.

• When you need testing:

• When you‟re writing new code, you can use tests to validate your code works as expected.

• When you‟re refactoring or modifying old code, you can use tests to ensure your changes haven‟t affected your application‟s behavior unexpectedly.

• Writing tests: (write in tests.py)

• Unit tests (important!, mostly use)

• Doctests (just for simple tasks)

23/08/2012 Python - Django Training Course 2012 @HCMUT 153

Testing Django App. (cont.)

• Running test:

23/08/2012 Python - Django Training Course 2012 @HCMUT 154

Testing Django App. (cont.)

• The test database:

• Tests that require a database (namely, model tests) will not use your "real" (production) database. Separate, blank databases are created for the tests.

• Regardless of whether the tests pass or fail, the test databases are destroyed when all the tests have been executed.

• Understanding test outputs:

23/08/2012 Python - Django Training Course 2012 @HCMUT 155

Testing Django App. (cont.)

• Test tools: if you want, look more info at (2):

• the test Client

• making request

• testing response

• Exceptions

• request factory

• URL configuration

23/08/2012 Python - Django Training Course 2012 @HCMUT 156

Sending Email

• Testing on localhost:

• In settings.py:

• EMAIL_HOST = 'localhost'

• EMAIL_PORT = 1025

• Open a command-line: python -m smtpd -n -c DebuggingServer localhost:1025

• Sending email with your Gmail account

• In settings.py:

• EMAIL_HOST = 'smtp.gmail.com'

• EMAIL_HOST_USER = 'abc@gmail.com'

• EMAIL_HOST_PASSWORD = 'yourpass'

• EMAIL_PORT = 587 # Check on the Internet if not successful

• EMAIL_USER_TLS = True # Gmail now accepts HTTPS only

23/08/2012 Python - Django Training Course 2012 @HCMUT 157

Sending Email (cont.) • in views.py:

• send_mail(subject, message, from_email, recipient_list, fail_silently=False,auth_user=None, auth_password=None, connection=None)

• send_mass_mail(datatuple, fail_silently=False, auth_user=None,auth_password=None, connection=None)

• mail_admins(subject, message, fail_silently=False, connection=None,html_message=None)

• mail_managers(subject, message, fail_silently=False, connection=None,html_message=None)

23/08/2012 Python - Django Training Course 2012 @HCMUT 158

Sending Email (cont.)

• Prevent Header injection: - handling email form

23/08/2012 Python - Django Training Course 2012 @HCMUT 159

Pagination

• In views.py:

23/08/2012 Python - Django Training Course 2012 @HCMUT 160

Pagination (Cont.)

• in templates (html files)

23/08/2012 Python - Django Training Course 2012 @HCMUT 161

Turn Debug mode off

• in settings.py, you set TEMPLATE_DEBUG and DEBUG to False

• write 404.html

23/08/2012 Python - Django Training Course 2012 @HCMUT 162

Turn Debug mode off (cont.)

• And write 500.html template

• Setting up Error alert:

23/08/2012 Python - Django Training Course 2012 @HCMUT 163

Other topics - Exercise

• Create a page for user authentication, when user authenticated, they will see “authenticated_page.html” that you can write anything that you want.

• Write unit test for some functions in Query Set's exercise

• In the Django Templates' exercise, add function send to my email button to send result of searching employee given name or ssn or bdate

• If the result in search employee is above 5, use pagination to cut off the display to another pages.

23/08/2012 Python - Django Training Course 2012 @HCMUT 164

23/08/2012 Python - Django Training Course 2012 @HCMUT 165

Contents

Part 1: Introduction to Python/Django

Part 2: HTML + CSS + JavaScript

Part 3: Installation & Configuration

Part 4: Models

Part 5: QuerySets

Part 6: Admin Sites

Part 7: URL Configuration and Request/Response (Views)

Part 8: Software development support

Part 9: Django Templates

Part 10: Forms

Part 11: File Uploads and Generic View

Part 12: Other topics

Part 13: Deployment

PART 13 - DEPLOYMENT Time to attract people to your website

23/08/2012 Python - Django Training Course 2012 @HCMUT 167

Outline

• Setup environment

• Use Virtualenv

• Deploy w/ Apache2 and Mod_WSGI

• Serve static files

23/08/2012 Python - Django Training Course 2012 @HCMUT 168

SETUP ENVIRONMENT

23/08/2012 Python - Django Training Course 2012 @HCMUT 169

Prerequisites

• Ubuntu (10.4 or newer) server or desktop

• Apache2

• Virtualenv

• Django 1.x and other libs on Virtualenv

23/08/2012 Python - Django Training Course 2012 @HCMUT 170

Installing Apache2

• Update the source list for newest version

> sudo apt-get update

• Install Apache2 and mod_wsgi

> sudo apt-get install apache2 libapache2-mod-wsgi

23/08/2012 Python - Django Training Course 2012 @HCMUT 171

Installing Virtualenv

• Install python setup tools and pip

> sudo apt-get install python-setuptools python-dev build-essential

> sudo apt-get install python-pip

• Install virtualenv

> pip install virtualenv

23/08/2012 Python - Django Training Course 2012 @HCMUT 172

USE VIRTUALENV

23/08/2012 Python - Django Training Course 2012 @HCMUT 173

What is Virtualenv?

• An isolated Python environment. Allows you to control which packages are used on a particular project by cloning your main Python.

• For example, you can run both Django 1.1 and Django 1.4 project on the same server with Virtualenv.

23/08/2012 Python - Django Training Course 2012 @HCMUT 174

Create a virtual environment

• The straight way

> virtualenv ~/.virtualenv/myenv

• If you want to use different Python version

> virtualenv --python=/usr/bin/python2.5 ~/.virtualenv/myenv

Note: ~/.virtualenv/myenv is just an example path, in fact you can create the environment at anywhere.

23/08/2012 Python - Django Training Course 2012 @HCMUT 175

Use it!

• Activate the virtual enviroment

> source ~/.virtualenv/myenv/bin/activate

• Deactivate

(myenv)> deactivate

• Install Django package

(myenv)> pip install django

• Install MySQL-Python

(myenv)> pip install mysql-python

23/08/2012 Python - Django Training Course 2012 @HCMUT 176

DEPLOY W/ APACHE2 AND

MOD_WSGI

23/08/2012 Python - Django Training Course 2012 @HCMUT 177

Components

23/08/2012 Python - Django Training Course 2012 @HCMUT 178

Apache Script WSGI Script

Django Project Directory

links to

links to

Apache script (Virtualhost)

• Copy the following script into /etc/apache2/sites-available/myproject

23/08/2012 Python - Django Training Course 2012 @HCMUT 179

<VirtualHost *:80> ServerName mysite.com, www.mysite.com CustomLog /var/logs/myproject-access_log common ErrorLog /var/logs/myproject-error_log Alias /home/user1/www/myproject/media <Directory /home/user1/www/myproject/static> Order allow,deny Options Indexes Allow from all </Directory> WSGIScriptAlias / /home/user1/www/myproject/myproject.wsgi </VirtualHost>

WSGI script

• Copy this into home/user1/www/myproject/myproject.wsgi

23/08/2012 Python - Django Training Course 2012 @HCMUT 180

import os import sys root_path = '/home/user1/www' project_path = '/home/user1/www/myproject' if root_path not in sys.path: sys.path.append(root_path) if project_path not in sys.path: sys.path.append(project_path) os.environ['DJANGO_SETTINGS_MODULE'] = „myproject.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()

Enable site

• Enable Apache script

> a2ensite myproject

• Restart Apache server

> sudo service apache2 restart

23/08/2012 Python - Django Training Course 2012 @HCMUT 181

Deployment - Outcome

• In Apache script, you have seen the line: ServerName mysite.com, www.mysite.com

• To access myproject.com site, in practice you need to buy a domain (myproject.com) and append DNS record to point to the server IP. It is beyond this course.

• You will test the deployment outcome in local server by configuring the host file. This is a very useful tip especially when you deploy the project before buying a domain.

• Tip: it’s the same technique used to by-pass Facebook blocking.

23/08/2012 Python - Django Training Course 2012 @HCMUT 182

Configure your host file

• Open the host file with nano

> sudo nano /etc/hosts

• Append 2 lines 127.0.0.1 myproject.com

127.0.0.1 www.myproject.com

• Press Ctrl+X and prompt Y to save the file

• Finally, open the browser at www.myproject.com.

23/08/2012 Python - Django Training Course 2012 @HCMUT 183

Deployment - Exercises

• Deploy your Django project with nginx (a different web server).

23/08/2012 Python - Django Training Course 2012 @HCMUT 184

Final Projects

• You can choose any topics from your own such as a social network or e-commerce websites... That must be contains almost all features or more that you learn from our course.

• Or you can complete all Exercises in this course about Employee Project management and add another functions if you don‟t have much time to do.

• If you do in groups, remember to use SVN for easy to maintain your codes.

23/08/2012 Python - Django Training Course 2012 @HCMUT 185

Django Dev.

Process • You can refer to this process to do your final project.

23/08/2012 Python - Django Training Course 2012 @HCMUT 186

Determine the functions

of your website

Design your database in ERD

and implements in models.py

Determine how many pages you

needed and url for each page,

then implements in urls.py

Design your base.html layout by

hand or by Photoshop

Implement your functions in

views.py, forms.py, admins.py Display your views to django

templates (.html) file

Complete your sites by adding css,

js, and other stuff

Run on localhost and testing, and

then deploy in a server

Recommended