• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Python/Django Training
 

Python/Django Training

on

  • 4,597 views

Python, django training

Python, django training

Statistics

Views

Total Views
4,597
Views on SlideShare
4,400
Embed Views
197

Actions

Likes
13
Downloads
223
Comments
0

14 Embeds 197

http://nguyenducminhkhoi.blogspot.com 163
http://bkitclub.net 13
http://www.admuncher.com 5
http://www.bkitclub.net 3
http://nguyenducminhkhoi.blogspot.jp 3
http://nguyenducminhkhoi.blogspot.pt 2
http://nguyenducminhkhoi.blogspot.kr 1
http://nguyenducminhkhoi.blogspot.in 1
http://nguyenducminhkhoi.blogspot.co.at 1
http://pinterest.com 1
http://nguyenducminhkhoi.blogspot.ru 1
http://nguyenducminhkhoi.blogspot.com.br 1
http://localhost 1
https://www.linkedin.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Python/Django Training Python/Django Training Presentation Transcript

    • PYTHON – DJANGOTRAININGBY: BKIT ATOM, Epsilon Mobile @ HCMC HCMUTSummer 2012Main reference:https://docs.djangoproject.com/en/1.4/Contact: bkitatom@gmail.com
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 2Instructors• 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 3Tools - 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 4Contents 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
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 5Introduction 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 6Introduction 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 7Overall 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 8Intro - 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 arent special enough to break the rules. • Although practicality beats purity.
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 9Intro - 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 youre Dutch.• Now is better than never. • Although never is often better than right now.• If the implementation is hard to explain, its a bad idea.• If the implementation is easy to explain, it may be a good idea.• Namespaces are one honking great idea -- lets do more of those!
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 10Web components
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 11Web Dev. Levels
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 12Intro - 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 13Intro – Python Exercise1. Write a program that continually reads integer numbersfrom the users until the user inputs value 0. After that, printout the average value of input numbers.2. Write a guess number game. Each launching, the programwill generate a random lucky number from 1 to 100. Afterthat, the program will ask the user for a guess number. If theguess number is greater than the lucky number, it will printout “Too high”; if the guess number is less than the luckynumber, it will print out “Too low”. The program will continueto ask a new guess number until the user enters the luckynumber. As a consequence, it will print out “You guess right! Itcosts you x guesses”, where x is the number of guesses theuser tries.
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 14Intro – Python Exercise (cont.)3. Write a dictionary program (use Dictionary type). Whenlaunching, the users can choose 3 options from the mainmenu: a. Search a word b. Import dictionary c. Exit- If the user chooses Search a word, it will require him toenter a word, then, it will print out the definition of thisword and return the main menu.- If the user chooses Import dictionary, it will require himto enter the path of dictionary file. After that, it willimport words and definitions in the file into the programdictionary. Finally, it returns the main menu.- If the user chooses Exit, the program will terminateimmediately. The dictionary file is a plain text file with thefollowing format:
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 15Intro – Python Exercise (cont.)4. Write a student management program (use Class). Astudent has 5 fields of information: ID, Name, Class,DOB (Date of Birth), GPA (Grade Point Average). Theprogram will have 4 options from the main menu:a. Explore all studentsb. Add new studentc. Remove a studentd. Exit- Explore all students: prints out all students with theirinformation.- Add new student: requires the user to enter theinformation for new student.- Remove a student: removes a student by ID.- Exit: terminates the program.
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 16Contents 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
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 17HTML + CSS + JavaScript• (1) HTML + CSS slides: http://www.mediafire.com/?30r202gu4b2csgo• (2) JavaScript + jQuery slides: http://www.slideshare.net/ducminhkhoi/training-javascript- 2012-hcmut• (3) For complete tutorial and reference, please refer to this page: http://www.w3schools.com/ section (HTML, HTML5, CSS, CSS3, JavaScript, jQuery, Ajax)
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 18HTML + 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 19Exercise• 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 20Contents 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
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 21Installation & 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 22Installation & Configuration - Outcomes• Setup successfully according to the guides• Understand Django Structure Directories and functions.
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 23Exercise• Complete your own configure and projects.• Write Hello World project to test your work!
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 24Contents 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
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 25Models - 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 26Models - 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 27 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 28How things in Django works?
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 29Models• 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 30Models (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 31Models (cont.)• Review SQL Statements: • DML (Data Manipulation Language)
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 32Models (cont.)• Field types • The database column type (e.g. INTEGER, VARCHAR). • The widget to use in Djangos admin interface, if you care to use it (e.g. <input type="text">,<select>). • The minimal validation requirements, used in Djangos admin and in automatically-generated forms.
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 33Models (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 34Models (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 35Models (cont.) Can have recursive relationship
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 36Models (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 37Models (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 38Models (cont.)• Override predefined method:• Notice: • call the superclass method -- thats 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 -- thats 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 39Models (cont.)• Model fields: Please refer to: https://docs.djangoproje ct.com/en/1.4/ref/model s/fields/ for more details
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 40Models (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 41Contents 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
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 42QuerySet – 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 43QuerySet – Outcome• Make sure after this training, you understand:
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 44QuerySet API
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 45QuerySet API
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 46QuerySet –Example1• We will have 3 model:#without inheritance from models.Model classclass 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__ functionclass 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 47QuerySet-Using python shellLet‟s start create some objects!!!
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 48QuerySet-Exercises1:Using Student3 model, create35 students who has name isin form: one lowercase letterand its uppercase, email inform “[name]@mysite.com”For example:
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 49QuerySet- with relationsGender_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.nameclass Song(models.Model): name = models.CharField(max_length=200) article = models.ForeignKey(to=Article,related_name=composed) def __unicode__(self): return "song: %s" %self.nameclass 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 50QuerySet-wit relations(2)
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 51QuerySet-with relations (3)
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 52QuerySet- exercisesclass 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.nameGender_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 53QuerySet – 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 54QuerySet – 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 55 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 otheremployees+ Filter all departments that manages by employees that work forproject with specific id( you can choose whatever id you want)• DELETING+ Delete a given employee with name+ Delete all Psychology moviesNote: please capture your screens when doing those steps andadd them to your report (doc or pdf file).
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 56Contents 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
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 57Admin 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 58Admin 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 59 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 60 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_CONT EXT_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 61Admin 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 62Admin 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 63Admin sites (cont.) – ModelAdmin Actions
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 64Admin sites (cont.) – ModelAdmin• ModelAdmin.exclude• ModelAdmin.fields
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 65Admin sites (cont.) – ModelAdmin• ModelAdmin.fieldsets
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 66Admin sites (cont.) – ModelAdmin• ModelAdmin.list_display ModelAdmin.list_display_links ModelAdmin.list_editable
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 67Admin sites (cont.) – ModelAdmin• ModelAdmin.list_filter• ModelAdmin.search_fields
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 68Admin 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 69Admin 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 70Admin sites (cont.)• Overriding admin templates, see more at documents!
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 71Admin sites (cont.) - HomeworkAdmin page+ Add all of the models above to admin site.+ Manage projects of a department by StackInline+ Manage department managed by an employee byTabularInline+ Add all below actions to admin page: - Filter all employees with odd id - Filter all employees with total timework ismore than 40 hours - Filter all projects which total salary ofworker is more than 500usd
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 72Contents 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
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 73 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 74URLs & 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 75How things in Django works?
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 76Regular 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 77Some 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 78How 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 79How to use RE in python
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 80URL 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 81URL – 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 82URL – 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 83URL – non-named/named groups
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 84URL - 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 85URL – view prefix
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 86URL - 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 87Writing 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 88Request/ 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 89Request/ 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 90Request/ 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 91Django shortcut functions• 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.
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 92Django 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 93Django 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 94Django shortcut functions (cont.)
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 95Homework• 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 96Contents 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
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 97Dev. Tools - references• (1) Please refer to this document: http://www.mediafire.com/view/?x074zrdwd40g4u7
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 98Dev. 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 99Software 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 100Contents 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
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 101 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 102Django 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 103Templates• 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 104Variable• Syntax: {{ variable }} i = 1, j = 2 <p> This is line {{ i }}</p> <p> This is line 1</p> <p> This is line {{ j }}</p> <p> This is line 3</p> class book(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=35) obj = book(title = “My life”, author = “Unknow”) <h3> {{ obj.title }} </h3> <h3> My life </h3> <p> {{ obj.author }} </p> <p> Unknow </p> obj can be a non-parametric function
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 105Filters• Use filters to modify variables for display• Syntax: {{ variable | filter [| filter …] }} value1 = “” value2 = [1, 4, 2, 6] <p>{{ value1 | default: "nothing" }}</p> <p> nothing </p> <p> Length: {{ value2 | length }}</p> <p> Length: 4 </p> More: https://docs.djangoproject.com/en/1.4/ref/templates/builtins /#ref-templates-builtins-filters https://docs.djangoproject.com/en/1.4/howto/custom- template-tags/
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 106Tags• Syntax: • {% tag %} • {% tag %} ... tag contents ... {% endtag %} {% if list | length > 0 %} List: {% for i in list %} {{ i }} {% endfor %} {% else %} List is empty {% endif %} 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 107Tags: inheritance• base.html <p>This is a example</p> <title>{% block title %}My site{% endblock %}</title> <div>{% block content %} {% endblock %}</div>• template.html {% extends "base.html" %} {% block title %}Welcome !{% endblock %} {% block content %} <ul> {% for i in [1, 2] %} <li>This is line {{ i }}</li> {% endfor %} </ul> {% endblock %}
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 108Tags: inheritance• template.html <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>
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 109EscapeExample: {{ obj }}obj = <b>Bold</b>This will be escaped: <b>Bold</b>This will not be escaped: BoldBlock autoescape {% autoescape on %} {% autoescape off %} Example {{ obj }} Example {{ obj }} {% endautoescape %} {% endautoescape %} Example <b>Bold</b> Example Bold
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 110Loading templates setting.py template.html TEMPLATE_DIR = ( <p> This is a book </p> “mysite/app/template”, <p> Title: {{ book.title }} </p> “home/default”, <p> Author: {{ book.author }}</p> ) views.py 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: My life </p> <p> Author: H.Anh </p>
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 111Django 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 112Contents 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
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 113 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/modelfor ms/
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 114Forms - 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 115Form 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 116Using 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 117Processing 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 its valid.
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 118Displaying 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 119Customizing the form template
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 120Looping over the forms fields• {{ field.label }}• {{ field.label_tag }}• {{ field.value }}• {{ field.html_name }}• {{ field.help_text }}• {{ field.errors }}
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 121Form fields – core fields argument• required• label:
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 122Form fields – core fields argument• initial:• help_text:• Error_messages:
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 123Form fields – built in fields classes• BooleanField • IntegerField• CharField • IPAddressField• ChoiceField • GenericIPAddressField• TypedChoiceField • MultipleChoiceField• DateField • TypedMultipleChoiceFi• DateTimeField eld• DecimalField• EmailField • NullBooleanField• FileField • RegexField• FilePathField • SlugField• FloatField • TimeField• ImageField • URLField
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 124ModelForms• Make form directly from models• Fields type conversion: see more at: https://docs.djangoproject.com/en/1.4/topics/forms/modelfo rms/#field-types
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 125ModelForms• 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 doesnt validate -- i.e., if form.errors evaluates to True. • If you call save() with commit=False, then it will return an object that hasnt 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 126ModelForms – customize• Overriding the default field types or widgets:
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 127Forms – 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 128Contents 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
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 129 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 130File 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 131File Uploads• Conditions in templates to use: • enctype="multipart/form-data“ • method was POST
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 132Handling 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 133Storage 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 134Outputting PDF• Install ReportLab:• Write your view
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 135Generic 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 136Generic 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 137Generic Views (cont.)• list_detail.object_list e.g
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 138Generic Views (cont.)• Other necessary fields:
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 139Generic Views (cont.)• To build a list page of all publishers• In the absence of an explicit template Django will infer one from the objects 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 140Generic Views (cont.)• Other generic views should know: • Simple generic views • View • TemplateView • RedirectView • Detail views • DetailView • List views • ListView
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 141File 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 142Contents 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
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 143 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=o lddocs• (3) Sending Email: https://docs.djangoproject.com/en/dev/topics/email/• (4) Pagination: https://docs.djangoproject.com/en/dev/topics/pagination/?fro m=olddocs• (5) Turn off debug modes: http://djangobook.com/en/2.0/chapter12/
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 144Other topics - Outcomes• Understand clearly and apply these information in your project, exercises.
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 145User 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 146 User authentication (cont.)• Class models.User has fields: • username • Class models.User has methods: • first_name • is_anonymous() • last_name • is_authenticated() • email • get_full_name() • password • is_staff • set_password() • is_active • check_password(raw_password) • is_superuser • get_all_permissions(obj=None) • last_login • email_user(subject, message, from • date_joined _email=None) • get_profile()• Class models.UserManager has helper functions: • create_user(username, email=None, password=None) • make_random_password(length=10,allowed_chars=abcdefghjkmn pqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789)
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 147User authentication (cont.) • Usage: • creating users: • changing password: • creating superuser:
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 148User 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 149User authentication (cont.)• How to log a user in: • Authenticate() and login(): • logout():
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 150User authentication (cont.)• Limiting access – login_required decorator: • decorators.login_required([redirect_field_name=REDI RECT_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 151User 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, authentic ation_form]) • logout(request[, next_page, template_name, redirect_field_na me]) • logout_then_login(request[, login_url]) • password_change(request[, template_name, post_change_redire ct,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 152User authentication (cont.)• Built-in forms: • class AdminPasswordChangeForm: A form used in the admin interface to change a users 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 users 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 users information and permissions. • class UserCreationForm: A form for creating a new user.
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 153Testing 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 154Testing Django App. (cont.)• Running test:
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 155Testing 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 156Testing 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 157Sending 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 158Sending Email (cont.)• in views.py:• send_mail(subject, message, from_email, recipient_list, fail_silently=F alse,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=No ne,html_message=None)
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 159Sending Email (cont.)• Prevent Header injection: - handling email form
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 160Pagination• In views.py:
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 161Pagination (Cont.)• in templates (html files)
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 162Turn 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 163Turn Debug mode off (cont.)• And write 500.html template• Setting up Error alert:
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 164Other 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 Sets 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 165Contents 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
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 166 Deployment - References• (1) How to use Django with Apache and mod_wsgi https://docs.djangoproject.com/en/1.3/howto/deployment/mo dwsgi/• (2) Notes on using pip and virtualenv with Django http://www.saltycrane.com/blog/2009/05/notes-using-pip- and-virtualenv-django/
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 167 PART 13 - DEPLOYMENT Time to attract people to your website
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 168Outline• Setup environment• Use Virtualenv• Deploy w/ Apache2 and Mod_WSGI• Serve static files
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 169 SETUP ENVIRONMENT
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 170Prerequisites• 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 171Installing 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 172Installing 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 173 USE VIRTUALENV
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 174What 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 175Create a virtual environment• The straight way> virtualenv ~/.virtualenv/myenv• If you want to use different Python version> virtualenv --python=/usr/bin/python2.5~/.virtualenv/myenvNote: ~/.virtualenv/myenv is just an example path,in fact you can create the environment atanywhere.
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 176Use 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 177 DEPLOY W/ APACHE2 AND MOD_WSGI
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 178Components links to Apache Script WSGI Script links to Django Project Directory
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 179Apache script (Virtualhost)• Copy the following script into /etc/apache2/sites- available/myproject <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>
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 180WSGI script• Copy this into home/user1/www/myproject/myproject.wsgi 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()
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 181Enable site• Enable Apache script> a2ensite myproject• Restart Apache server> sudo service apache2 restart
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 182Deployment - 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 183Configure your host file• Open the host file with nano> sudo nano /etc/hosts• Append 2 lines127.0.0.1 myproject.com127.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 184Deployment - Exercises• Deploy your Django project with nginx (a different web server).
    • 23/08/2012 Python - Django Training Course 2012 @HCMUT 185Final 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 186Django Dev. Determine the functions of your websiteProcess Design your database in ERD and implements in models.py• You can refer to this process to do your Determine how many pages you final project. 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