SlideShare una empresa de Scribd logo
1 de 186
Descargar para leer sin conexión
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
23/08/2012            Python - Django Training Course 2012 @HCMUT   2




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   3




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   4




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
23/08/2012            Python - Django Training Course 2012 @HCMUT   5




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   6




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   7




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   8




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   9




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   10




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




Web Dev. Levels
23/08/2012             Python - Django Training Course 2012 @HCMUT   12




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   13




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   14




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   15




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   16




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
23/08/2012             Python - Django Training Course 2012 @HCMUT   17




HTML + 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   18




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   19




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   20




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
23/08/2012             Python - Django Training Course 2012 @HCMUT   21




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   22




Installation & Configuration - Outcomes
• Setup successfully according to the guides
• Understand Django Structure Directories and
 functions.
23/08/2012          Python - Django Training Course 2012 @HCMUT   23




Exercise
• Complete your own configure and projects.
• Write Hello World project to test your work!
23/08/2012                    Python - Django Training Course 2012 @HCMUT   24




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
23/08/2012             Python - Django Training Course 2012 @HCMUT   25




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   26




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   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   28




How things in Django works?
23/08/2012               Python - Django Training Course 2012 @HCMUT   29




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   30




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   31




Models (cont.)
• Review SQL Statements:
  • DML (Data Manipulation Language)
23/08/2012                     Python - Django Training Course 2012 @HCMUT   32




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   33




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   34




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   35




Models (cont.)
                                       Can have recursive
                                       relationship
23/08/2012                Python - Django Training Course 2012 @HCMUT   36




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   37




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   38




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   39

Models (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   40



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   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
23/08/2012             Python - Django Training Course 2012 @HCMUT   42




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   43




QuerySet – Outcome
• Make sure after this training, you understand:
23/08/2012     Python - Django Training Course 2012 @HCMUT   44




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




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




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   47




QuerySet-Using python shell




Let‟s start create some objects!!!
23/08/2012                Python - Django Training Course 2012 @HCMUT   48




QuerySet-Exercises1:


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:
23/08/2012                   Python - Django Training Course 2012 @HCMUT   49



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   50




QuerySet-wit relations(2)
23/08/2012    Python - Django Training Course 2012 @HCMUT   51



QuerySet-with relations (3)
23/08/2012                         Python - Django Training Course 2012 @HCMUT   52




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   53




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   54




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   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 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   56




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
23/08/2012               Python - Django Training Course 2012 @HCMUT   57




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   58




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   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   61




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   62




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   63




Admin sites (cont.) – ModelAdmin Actions
23/08/2012             Python - Django Training Course 2012 @HCMUT   64




Admin sites (cont.) – ModelAdmin
• ModelAdmin.exclude
• ModelAdmin.fields
23/08/2012         Python - Django Training Course 2012 @HCMUT   65




Admin sites (cont.) – ModelAdmin
• ModelAdmin.fieldsets
23/08/2012          Python - Django Training Course 2012 @HCMUT   66


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



                                           ModelAdmin.list_display_links
                                           ModelAdmin.list_editable
23/08/2012                 Python - Django Training Course 2012 @HCMUT   67


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




• ModelAdmin.search_fields
23/08/2012               Python - Django Training Course 2012 @HCMUT   68




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   69




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   70




Admin sites (cont.)
• Overriding admin templates, see more at
 documents!
23/08/2012         Python - Django Training Course 2012 @HCMUT   71




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   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
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   74




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   75




How things in Django works?
23/08/2012           Python - Django Training Course 2012 @HCMUT   76




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   77




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   78




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   79




How to use RE in python
23/08/2012         Python - Django Training Course 2012 @HCMUT   80




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   81




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   82




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   83




URL – non-named/named groups
23/08/2012             Python - Django Training Course 2012 @HCMUT   84




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   85




URL – view prefix
23/08/2012          Python - Django Training Course 2012 @HCMUT   86




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   87




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   88




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   89




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   90




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   91




Django 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   92



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   93




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   94




Django shortcut functions (cont.)
23/08/2012          Python - Django Training Course 2012 @HCMUT   95




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   96




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
23/08/2012           Python - Django Training Course 2012 @HCMUT   97




Dev. Tools - references
• (1) Please refer to this document:
  http://www.mediafire.com/view/?x074zrdwd40g4u7
23/08/2012           Python - Django Training Course 2012 @HCMUT   98




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   99




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   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
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   102




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   103




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   104




Variable
• 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   105




Filters
• 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   106




Tags
• 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   107




Tags: 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   108




Tags: 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   109




Escape
Example: {{ obj }}
obj = <b>Bold</b>

This will be escaped:          <b>Bold</b>

This will not be escaped:           Bold


Block 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   110




Loading 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   111




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   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
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   114




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   115




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   116


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   117




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   118




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   119




Customizing the form template
23/08/2012                Python - Django Training Course 2012 @HCMUT   120




Looping over the form's 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   121




Form fields – core fields argument
• required




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


Form fields – core fields argument
• initial:




• help_text:




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




Form 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   124




ModelForms
• 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   125




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   126




ModelForms – customize




• Overriding the default field types or widgets:
23/08/2012               Python - Django Training Course 2012 @HCMUT   127




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   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
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   130




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   131



File Uploads


• Conditions in templates to use:
  • enctype="multipart/form-data“
  • method was POST
23/08/2012             Python - Django Training Course 2012 @HCMUT   132




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   133




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   134


Outputting PDF
• Install ReportLab:




• Write your view
23/08/2012                Python - Django Training Course 2012 @HCMUT   135




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   136




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   137




Generic Views (cont.)




•                       list_detail.object_list e.g
23/08/2012          Python - Django Training Course 2012 @HCMUT   138




Generic Views (cont.)
• Other necessary fields:
23/08/2012                   Python - Django Training Course 2012 @HCMUT   139




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   140




Generic 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   141




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   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
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   144




Other topics - Outcomes
• Understand clearly and apply these information in
 your project, exercises.
23/08/2012              Python - Django Training Course 2012 @HCMUT   145




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   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   147




User authentication (cont.)
  • Usage:
    • creating users:




     • changing password:




     • creating superuser:
23/08/2012               Python - Django Training Course 2012 @HCMUT   148




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   149




User authentication (cont.)
• How to log a user in:
     • Authenticate() and login():




     • logout():
23/08/2012                 Python - Django Training Course 2012 @HCMUT   150




User 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   151


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, 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   152




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   153




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   154




Testing Django App. (cont.)
• Running test:
23/08/2012              Python - Django Training Course 2012 @HCMUT   155




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   156




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   157




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   158



Sending 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   159




Sending Email (cont.)
• Prevent Header injection: - handling email form
23/08/2012       Python - Django Training Course 2012 @HCMUT   160




Pagination
• In views.py:
23/08/2012           Python - Django Training Course 2012 @HCMUT   161




Pagination (Cont.)
• in templates (html files)
23/08/2012         Python - Django Training Course 2012 @HCMUT   162




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   163




Turn Debug mode off (cont.)
• And write 500.html template




• Setting up Error alert:
23/08/2012          Python - Django Training Course 2012 @HCMUT   164




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   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
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   168




Outline
• 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   170




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   171




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   172




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   173




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




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   175




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   176




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   177




  DEPLOY W/ APACHE2 AND
  MOD_WSGI
23/08/2012             Python - Django Training Course 2012 @HCMUT   178




Components


                        links to
       Apache Script                                  WSGI Script




                                                   links to

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




Apache 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   180




WSGI 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   181




Enable site
• Enable Apache script
> a2ensite myproject
• Restart Apache server
> sudo service apache2 restart
23/08/2012             Python - Django Training Course 2012 @HCMUT   182




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   183




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   184




Deployment - Exercises
• Deploy your Django project with nginx (a different
 web server).
23/08/2012          Python - Django Training Course 2012 @HCMUT   185




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                          186


Django Dev.                                       Determine the functions
                                                      of your website


Process                                      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

Más contenido relacionado

La actualidad más candente

Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...Edureka!
 
Full stack devlopment using django main ppt
Full stack devlopment using django main pptFull stack devlopment using django main ppt
Full stack devlopment using django main pptSudhanshuVijay3
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To DjangoJay Graves
 
Django Framework and Application Structure
Django Framework and Application StructureDjango Framework and Application Structure
Django Framework and Application StructureSEONGTAEK OH
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and DjangoMichael Pirnat
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flaskjuzten
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC FrameworkBala Kumar
 
Overview of React.JS - Internship Presentation - Week 5
Overview of React.JS - Internship Presentation - Week 5Overview of React.JS - Internship Presentation - Week 5
Overview of React.JS - Internship Presentation - Week 5Devang Garach
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to djangoIlian Iliev
 
The Full Stack Web Development
The Full Stack Web DevelopmentThe Full Stack Web Development
The Full Stack Web DevelopmentSam Dias
 
Introduction To Single Page Application
Introduction To Single Page ApplicationIntroduction To Single Page Application
Introduction To Single Page ApplicationKMS Technology
 

La actualidad más candente (20)

Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...
 
Full stack devlopment using django main ppt
Full stack devlopment using django main pptFull stack devlopment using django main ppt
Full stack devlopment using django main ppt
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To Django
 
Django Framework and Application Structure
Django Framework and Application StructureDjango Framework and Application Structure
Django Framework and Application Structure
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
Flask
FlaskFlask
Flask
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flask
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC Framework
 
Django Girls Tutorial
Django Girls TutorialDjango Girls Tutorial
Django Girls Tutorial
 
Angular 14.pptx
Angular 14.pptxAngular 14.pptx
Angular 14.pptx
 
Overview of React.JS - Internship Presentation - Week 5
Overview of React.JS - Internship Presentation - Week 5Overview of React.JS - Internship Presentation - Week 5
Overview of React.JS - Internship Presentation - Week 5
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
 
The Full Stack Web Development
The Full Stack Web DevelopmentThe Full Stack Web Development
The Full Stack Web Development
 
React Django Presentation
React Django PresentationReact Django Presentation
React Django Presentation
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Introduction To Single Page Application
Introduction To Single Page ApplicationIntroduction To Single Page Application
Introduction To Single Page Application
 

Destacado

Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in PythonJuan-Manuel Gimeno
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
 
Advanced Django Forms Usage
Advanced Django Forms UsageAdvanced Django Forms Usage
Advanced Django Forms UsageDaniel Greenfeld
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksShawn Rider
 
Getting Started With Django
Getting Started With DjangoGetting Started With Django
Getting Started With Djangojeff_croft
 
Verilerimi düzenliyorum
Verilerimi düzenliyorumVerilerimi düzenliyorum
Verilerimi düzenliyorumİsmail Keskin
 

Destacado (20)

Wordnet Introduction
Wordnet IntroductionWordnet Introduction
Wordnet Introduction
 
Training Google Drive and Hangouts.pptx
Training Google Drive and Hangouts.pptxTraining Google Drive and Hangouts.pptx
Training Google Drive and Hangouts.pptx
 
Training basic latex
Training basic latexTraining basic latex
Training basic latex
 
Training javascript 2012 hcmut
Training javascript 2012 hcmutTraining javascript 2012 hcmut
Training javascript 2012 hcmut
 
Ubuntu – Linux Useful Commands
Ubuntu – Linux Useful CommandsUbuntu – Linux Useful Commands
Ubuntu – Linux Useful Commands
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Gioi thieu truong bk
Gioi thieu truong bkGioi thieu truong bk
Gioi thieu truong bk
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in Python
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
Advanced Django Forms Usage
Advanced Django Forms UsageAdvanced Django Forms Usage
Advanced Django Forms Usage
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Python Worst Practices
Python Worst PracticesPython Worst Practices
Python Worst Practices
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, Tricks
 
Getting Started With Django
Getting Started With DjangoGetting Started With Django
Getting Started With Django
 
Verilerimi düzenliyorum
Verilerimi düzenliyorumVerilerimi düzenliyorum
Verilerimi düzenliyorum
 
Dili kullanmak
Dili kullanmakDili kullanmak
Dili kullanmak
 
Phương pháp học đại học
Phương pháp học đại họcPhương pháp học đại học
Phương pháp học đại học
 
Advanced Django
Advanced DjangoAdvanced Django
Advanced Django
 
Django in the Real World
Django in the Real WorldDjango in the Real World
Django in the Real World
 

Similar a Python/Django Training

Company Visitor Management System Report.docx
Company Visitor Management System Report.docxCompany Visitor Management System Report.docx
Company Visitor Management System Report.docxfantabulous2024
 
Learn to Code with MIT App Inventor ( PDFDrive ).pdf
Learn to Code with MIT App Inventor ( PDFDrive ).pdfLearn to Code with MIT App Inventor ( PDFDrive ).pdf
Learn to Code with MIT App Inventor ( PDFDrive ).pdfNemoPalleschi
 
Algorithms and Application Programming
Algorithms and Application ProgrammingAlgorithms and Application Programming
Algorithms and Application Programmingahaleemsl
 
Android Architecture, Environment, and Components.pptx
Android Architecture, Environment, and Components.pptxAndroid Architecture, Environment, and Components.pptx
Android Architecture, Environment, and Components.pptxHasanulFahmi2
 
Django interview Questions| Edureka
Django interview  Questions| EdurekaDjango interview  Questions| Edureka
Django interview Questions| EdurekaEdureka!
 
Odoo Experience 2018 - Odoo Studio: A Functional Approach
Odoo Experience 2018 - Odoo Studio: A Functional ApproachOdoo Experience 2018 - Odoo Studio: A Functional Approach
Odoo Experience 2018 - Odoo Studio: A Functional ApproachElínAnna Jónasdóttir
 
Django tutorial
Django tutorialDjango tutorial
Django tutorialKsd Che
 
By the power of Plone - Case Carousel at University of Jyväskylä
By the power of Plone - Case Carousel at University of JyväskyläBy the power of Plone - Case Carousel at University of Jyväskylä
By the power of Plone - Case Carousel at University of JyväskyläRikupekka Oksanen
 
Collaboration Portal for Researchers
Collaboration Portal for ResearchersCollaboration Portal for Researchers
Collaboration Portal for ResearchersFatemeh Khast Khoda
 
Webinar on How to use MyAppConverter
Webinar on How to use  MyAppConverterWebinar on How to use  MyAppConverter
Webinar on How to use MyAppConverterJaoued Ahmed
 
How to become a software developer
How to become a software developerHow to become a software developer
How to become a software developerEyob Lube
 
Eca online-seminar-session-1.pptx
Eca online-seminar-session-1.pptxEca online-seminar-session-1.pptx
Eca online-seminar-session-1.pptxGoran Djonovic
 
CV_NgoQuocVuong
CV_NgoQuocVuongCV_NgoQuocVuong
CV_NgoQuocVuongVuong Ngo
 
Workshop: Introduction to Web Components & Polymer
Workshop: Introduction to Web Components & Polymer Workshop: Introduction to Web Components & Polymer
Workshop: Introduction to Web Components & Polymer John Riviello
 
AstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdf
AstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdfAstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdf
AstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdfFarHanWasif1
 
Learn-N-Grow An interactive E Learning Platform Presentation
Learn-N-Grow An interactive E Learning Platform PresentationLearn-N-Grow An interactive E Learning Platform Presentation
Learn-N-Grow An interactive E Learning Platform PresentationRohitChaurasia36
 
CTE 323 - Lecture 1.pptx
CTE 323 - Lecture 1.pptxCTE 323 - Lecture 1.pptx
CTE 323 - Lecture 1.pptxOduniyiAdebola
 

Similar a Python/Django Training (20)

Company Visitor Management System Report.docx
Company Visitor Management System Report.docxCompany Visitor Management System Report.docx
Company Visitor Management System Report.docx
 
Learn to Code with MIT App Inventor ( PDFDrive ).pdf
Learn to Code with MIT App Inventor ( PDFDrive ).pdfLearn to Code with MIT App Inventor ( PDFDrive ).pdf
Learn to Code with MIT App Inventor ( PDFDrive ).pdf
 
Django - basics
Django - basicsDjango - basics
Django - basics
 
Django Documentation
Django DocumentationDjango Documentation
Django Documentation
 
Algorithms and Application Programming
Algorithms and Application ProgrammingAlgorithms and Application Programming
Algorithms and Application Programming
 
Django
DjangoDjango
Django
 
Android Architecture, Environment, and Components.pptx
Android Architecture, Environment, and Components.pptxAndroid Architecture, Environment, and Components.pptx
Android Architecture, Environment, and Components.pptx
 
Django interview Questions| Edureka
Django interview  Questions| EdurekaDjango interview  Questions| Edureka
Django interview Questions| Edureka
 
Odoo Experience 2018 - Odoo Studio: A Functional Approach
Odoo Experience 2018 - Odoo Studio: A Functional ApproachOdoo Experience 2018 - Odoo Studio: A Functional Approach
Odoo Experience 2018 - Odoo Studio: A Functional Approach
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
 
By the power of Plone - Case Carousel at University of Jyväskylä
By the power of Plone - Case Carousel at University of JyväskyläBy the power of Plone - Case Carousel at University of Jyväskylä
By the power of Plone - Case Carousel at University of Jyväskylä
 
Collaboration Portal for Researchers
Collaboration Portal for ResearchersCollaboration Portal for Researchers
Collaboration Portal for Researchers
 
Webinar on How to use MyAppConverter
Webinar on How to use  MyAppConverterWebinar on How to use  MyAppConverter
Webinar on How to use MyAppConverter
 
How to become a software developer
How to become a software developerHow to become a software developer
How to become a software developer
 
Eca online-seminar-session-1.pptx
Eca online-seminar-session-1.pptxEca online-seminar-session-1.pptx
Eca online-seminar-session-1.pptx
 
CV_NgoQuocVuong
CV_NgoQuocVuongCV_NgoQuocVuong
CV_NgoQuocVuong
 
Workshop: Introduction to Web Components & Polymer
Workshop: Introduction to Web Components & Polymer Workshop: Introduction to Web Components & Polymer
Workshop: Introduction to Web Components & Polymer
 
AstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdf
AstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdfAstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdf
AstroLabs_Academy_Learning_to_Code-Coding_Bootcamp_Day1.pdf
 
Learn-N-Grow An interactive E Learning Platform Presentation
Learn-N-Grow An interactive E Learning Platform PresentationLearn-N-Grow An interactive E Learning Platform Presentation
Learn-N-Grow An interactive E Learning Platform Presentation
 
CTE 323 - Lecture 1.pptx
CTE 323 - Lecture 1.pptxCTE 323 - Lecture 1.pptx
CTE 323 - Lecture 1.pptx
 

Más de University of Technology (10)

Basic probability & statistics
Basic probability & statisticsBasic probability & statistics
Basic probability & statistics
 
Introduction to gsa vietnam
Introduction to gsa vietnamIntroduction to gsa vietnam
Introduction to gsa vietnam
 
Phuong phap hoc tap on thi 2013
Phuong phap hoc tap on thi 2013Phuong phap hoc tap on thi 2013
Phuong phap hoc tap on thi 2013
 
Training python (new Updated)
Training python (new Updated)Training python (new Updated)
Training python (new Updated)
 
Introduction to WEB HTML, CSS
Introduction to WEB HTML, CSSIntroduction to WEB HTML, CSS
Introduction to WEB HTML, CSS
 
Training android
Training androidTraining android
Training android
 
Design patterns tutorials
Design patterns tutorialsDesign patterns tutorials
Design patterns tutorials
 
Phương pháp học tập official
Phương pháp học tập officialPhương pháp học tập official
Phương pháp học tập official
 
English Writing Skills
English Writing SkillsEnglish Writing Skills
English Writing Skills
 
Presentation bkit business
Presentation bkit businessPresentation bkit business
Presentation bkit business
 

Último

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 

Último (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Python/Django Training

  • 1. 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
  • 2. 23/08/2012 Python - Django Training Course 2012 @HCMUT 2 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)
  • 3. 23/08/2012 Python - Django Training Course 2012 @HCMUT 3 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
  • 4. 23/08/2012 Python - Django Training Course 2012 @HCMUT 4 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
  • 5. 23/08/2012 Python - Django Training Course 2012 @HCMUT 5 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/
  • 6. 23/08/2012 Python - Django Training Course 2012 @HCMUT 6 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
  • 7. 23/08/2012 Python - Django Training Course 2012 @HCMUT 7 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
  • 8. 23/08/2012 Python - Django Training Course 2012 @HCMUT 8 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.
  • 9. 23/08/2012 Python - Django Training Course 2012 @HCMUT 9 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!
  • 10. 23/08/2012 Python - Django Training Course 2012 @HCMUT 10 Web components
  • 11. 23/08/2012 Python - Django Training Course 2012 @HCMUT 11 Web Dev. Levels
  • 12. 23/08/2012 Python - Django Training Course 2012 @HCMUT 12 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
  • 13. 23/08/2012 Python - Django Training Course 2012 @HCMUT 13 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.
  • 14. 23/08/2012 Python - Django Training Course 2012 @HCMUT 14 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:
  • 15. 23/08/2012 Python - Django Training Course 2012 @HCMUT 15 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.
  • 16. 23/08/2012 Python - Django Training Course 2012 @HCMUT 16 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
  • 17. 23/08/2012 Python - Django Training Course 2012 @HCMUT 17 HTML + 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)
  • 18. 23/08/2012 Python - Django Training Course 2012 @HCMUT 18 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
  • 19. 23/08/2012 Python - Django Training Course 2012 @HCMUT 19 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.
  • 20. 23/08/2012 Python - Django Training Course 2012 @HCMUT 20 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
  • 21. 23/08/2012 Python - Django Training Course 2012 @HCMUT 21 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/
  • 22. 23/08/2012 Python - Django Training Course 2012 @HCMUT 22 Installation & Configuration - Outcomes • Setup successfully according to the guides • Understand Django Structure Directories and functions.
  • 23. 23/08/2012 Python - Django Training Course 2012 @HCMUT 23 Exercise • Complete your own configure and projects. • Write Hello World project to test your work!
  • 24. 23/08/2012 Python - Django Training Course 2012 @HCMUT 24 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
  • 25. 23/08/2012 Python - Django Training Course 2012 @HCMUT 25 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
  • 26. 23/08/2012 Python - Django Training Course 2012 @HCMUT 26 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.
  • 27. 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
  • 28. 23/08/2012 Python - Django Training Course 2012 @HCMUT 28 How things in Django works?
  • 29. 23/08/2012 Python - Django Training Course 2012 @HCMUT 29 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:
  • 30. 23/08/2012 Python - Django Training Course 2012 @HCMUT 30 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
  • 31. 23/08/2012 Python - Django Training Course 2012 @HCMUT 31 Models (cont.) • Review SQL Statements: • DML (Data Manipulation Language)
  • 32. 23/08/2012 Python - Django Training Course 2012 @HCMUT 32 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.
  • 33. 23/08/2012 Python - Django Training Course 2012 @HCMUT 33 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
  • 34. 23/08/2012 Python - Django Training Course 2012 @HCMUT 34 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.
  • 35. 23/08/2012 Python - Django Training Course 2012 @HCMUT 35 Models (cont.) Can have recursive relationship
  • 36. 23/08/2012 Python - Django Training Course 2012 @HCMUT 36 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:
  • 37. 23/08/2012 Python - Django Training Course 2012 @HCMUT 37 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.
  • 38. 23/08/2012 Python - Django Training Course 2012 @HCMUT 38 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.
  • 39. 23/08/2012 Python - Django Training Course 2012 @HCMUT 39 Models (cont.) • Model fields: Please refer to: https://docs.djangoproje ct.com/en/1.4/ref/model s/fields/ for more details
  • 40. 23/08/2012 Python - Django Training Course 2012 @HCMUT 40 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!
  • 41. 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
  • 42. 23/08/2012 Python - Django Training Course 2012 @HCMUT 42 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
  • 43. 23/08/2012 Python - Django Training Course 2012 @HCMUT 43 QuerySet – Outcome • Make sure after this training, you understand:
  • 44. 23/08/2012 Python - Django Training Course 2012 @HCMUT 44 QuerySet API
  • 45. 23/08/2012 Python - Django Training Course 2012 @HCMUT 45 QuerySet API
  • 46. 23/08/2012 Python - Django Training Course 2012 @HCMUT 46 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)
  • 47. 23/08/2012 Python - Django Training Course 2012 @HCMUT 47 QuerySet-Using python shell Let‟s start create some objects!!!
  • 48. 23/08/2012 Python - Django Training Course 2012 @HCMUT 48 QuerySet-Exercises1: 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:
  • 49. 23/08/2012 Python - Django Training Course 2012 @HCMUT 49 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
  • 50. 23/08/2012 Python - Django Training Course 2012 @HCMUT 50 QuerySet-wit relations(2)
  • 51. 23/08/2012 Python - Django Training Course 2012 @HCMUT 51 QuerySet-with relations (3)
  • 52. 23/08/2012 Python - Django Training Course 2012 @HCMUT 52 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
  • 53. 23/08/2012 Python - Django Training Course 2012 @HCMUT 53 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.
  • 54. 23/08/2012 Python - Django Training Course 2012 @HCMUT 54 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,
  • 55. 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 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).
  • 56. 23/08/2012 Python - Django Training Course 2012 @HCMUT 56 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
  • 57. 23/08/2012 Python - Django Training Course 2012 @HCMUT 57 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/
  • 58. 23/08/2012 Python - Django Training Course 2012 @HCMUT 58 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)
  • 59. 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.”
  • 60. 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).
  • 61. 23/08/2012 Python - Django Training Course 2012 @HCMUT 61 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:
  • 62. 23/08/2012 Python - Django Training Course 2012 @HCMUT 62 Admin sites (cont.) – ModelAdmin Options • ModelAdmin.actions_on_top • ModelAdmin.actions_on_bottom • ModelAdmin.actions_selection_counter • ModelAdmin.date_hierarchy
  • 63. 23/08/2012 Python - Django Training Course 2012 @HCMUT 63 Admin sites (cont.) – ModelAdmin Actions
  • 64. 23/08/2012 Python - Django Training Course 2012 @HCMUT 64 Admin sites (cont.) – ModelAdmin • ModelAdmin.exclude • ModelAdmin.fields
  • 65. 23/08/2012 Python - Django Training Course 2012 @HCMUT 65 Admin sites (cont.) – ModelAdmin • ModelAdmin.fieldsets
  • 66. 23/08/2012 Python - Django Training Course 2012 @HCMUT 66 Admin sites (cont.) – ModelAdmin • ModelAdmin.list_display ModelAdmin.list_display_links ModelAdmin.list_editable
  • 67. 23/08/2012 Python - Django Training Course 2012 @HCMUT 67 Admin sites (cont.) – ModelAdmin • ModelAdmin.list_filter • ModelAdmin.search_fields
  • 68. 23/08/2012 Python - Django Training Course 2012 @HCMUT 68 Admin sites (cont.) – ModelAdmin • ModelAdmin.list_max_show_all • ModelAdmin.list_per_page • ModelAdmin.list_select_related • ModelAdmin.ordering • ModelAdmin.paginator • ModelAdmin.save_as
  • 69. 23/08/2012 Python - Django Training Course 2012 @HCMUT 69 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
  • 70. 23/08/2012 Python - Django Training Course 2012 @HCMUT 70 Admin sites (cont.) • Overriding admin templates, see more at documents!
  • 71. 23/08/2012 Python - Django Training Course 2012 @HCMUT 71 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
  • 72. 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
  • 73. 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
  • 74. 23/08/2012 Python - Django Training Course 2012 @HCMUT 74 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
  • 75. 23/08/2012 Python - Django Training Course 2012 @HCMUT 75 How things in Django works?
  • 76. 23/08/2012 Python - Django Training Course 2012 @HCMUT 76 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
  • 77. 23/08/2012 Python - Django Training Course 2012 @HCMUT 77 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)
  • 78. 23/08/2012 Python - Django Training Course 2012 @HCMUT 78 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'
  • 79. 23/08/2012 Python - Django Training Course 2012 @HCMUT 79 How to use RE in python
  • 80. 23/08/2012 Python - Django Training Course 2012 @HCMUT 80 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
  • 81. 23/08/2012 Python - Django Training Course 2012 @HCMUT 81 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').
  • 82. 23/08/2012 Python - Django Training Course 2012 @HCMUT 82 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.
  • 83. 23/08/2012 Python - Django Training Course 2012 @HCMUT 83 URL – non-named/named groups
  • 84. 23/08/2012 Python - Django Training Course 2012 @HCMUT 84 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>)
  • 85. 23/08/2012 Python - Django Training Course 2012 @HCMUT 85 URL – view prefix
  • 86. 23/08/2012 Python - Django Training Course 2012 @HCMUT 86 URL - Passing extra options to view functions • In views.py, we have callback function: year_archive(request, year, foo)
  • 87. 23/08/2012 Python - Django Training Course 2012 @HCMUT 87 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.
  • 88. 23/08/2012 Python - Django Training Course 2012 @HCMUT 88 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)
  • 89. 23/08/2012 Python - Django Training Course 2012 @HCMUT 89 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.
  • 90. 23/08/2012 Python - Django Training Course 2012 @HCMUT 90 Request/ Response (cont.) • Usage: • HttpResponse subclasses • class HttpResponseRedirect • class HttpResponseBadRequest (400) • class HttpResponseNotFound (404) • class HttpResponseForbidden (403) • class HttpResponseServerError (500)
  • 91. 23/08/2012 Python - Django Training Course 2012 @HCMUT 91 Django 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.
  • 92. 23/08/2012 Python - Django Training Course 2012 @HCMUT 92 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.
  • 93. 23/08/2012 Python - Django Training Course 2012 @HCMUT 93 Django shortcut functions (cont.) • redirect(to[, permanent=False], *args, **kwargs): • Returns an HttpResponseRedirect to the appropriate URL for the arguments passed.
  • 94. 23/08/2012 Python - Django Training Course 2012 @HCMUT 94 Django shortcut functions (cont.)
  • 95. 23/08/2012 Python - Django Training Course 2012 @HCMUT 95 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.
  • 96. 23/08/2012 Python - Django Training Course 2012 @HCMUT 96 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
  • 97. 23/08/2012 Python - Django Training Course 2012 @HCMUT 97 Dev. Tools - references • (1) Please refer to this document: http://www.mediafire.com/view/?x074zrdwd40g4u7
  • 98. 23/08/2012 Python - Django Training Course 2012 @HCMUT 98 Dev. tools - outcomes • An overview of Software Development Process • Subversion - Working remotely with team (SVN) • Project Management Systems (Teamlab) • Bugs Tracker (Trello)
  • 99. 23/08/2012 Python - Django Training Course 2012 @HCMUT 99 Software dev. tools Exercise • You should you at least SVN in your Final Project when working with your partner.
  • 100. 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
  • 101. 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/
  • 102. 23/08/2012 Python - Django Training Course 2012 @HCMUT 102 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
  • 103. 23/08/2012 Python - Django Training Course 2012 @HCMUT 103 Templates • A template is simply a text file • A template contains: • Variables: get replaced with values • Tags: control the logic of the template
  • 104. 23/08/2012 Python - Django Training Course 2012 @HCMUT 104 Variable • 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
  • 105. 23/08/2012 Python - Django Training Course 2012 @HCMUT 105 Filters • 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/
  • 106. 23/08/2012 Python - Django Training Course 2012 @HCMUT 106 Tags • 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 #}
  • 107. 23/08/2012 Python - Django Training Course 2012 @HCMUT 107 Tags: 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 %}
  • 108. 23/08/2012 Python - Django Training Course 2012 @HCMUT 108 Tags: 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>
  • 109. 23/08/2012 Python - Django Training Course 2012 @HCMUT 109 Escape Example: {{ obj }} obj = <b>Bold</b> This will be escaped: <b>Bold</b> This will not be escaped: Bold Block autoescape {% autoescape on %} {% autoescape off %} Example {{ obj }} Example {{ obj }} {% endautoescape %} {% endautoescape %} Example <b>Bold</b> Example Bold
  • 110. 23/08/2012 Python - Django Training Course 2012 @HCMUT 110 Loading 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>
  • 111. 23/08/2012 Python - Django Training Course 2012 @HCMUT 111 Django Templates - Exercises • Write Django Templates for these page: • Search all employees according to given Name, SSN, Bdates (between X and Y)
  • 112. 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
  • 113. 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/
  • 114. 23/08/2012 Python - Django Training Course 2012 @HCMUT 114 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
  • 115. 23/08/2012 Python - Django Training Course 2012 @HCMUT 115 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.
  • 116. 23/08/2012 Python - Django Training Course 2012 @HCMUT 116 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.
  • 117. 23/08/2012 Python - Django Training Course 2012 @HCMUT 117 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.
  • 118. 23/08/2012 Python - Django Training Course 2012 @HCMUT 118 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:
  • 119. 23/08/2012 Python - Django Training Course 2012 @HCMUT 119 Customizing the form template
  • 120. 23/08/2012 Python - Django Training Course 2012 @HCMUT 120 Looping over the form's fields • {{ field.label }} • {{ field.label_tag }} • {{ field.value }} • {{ field.html_name }} • {{ field.help_text }} • {{ field.errors }}
  • 121. 23/08/2012 Python - Django Training Course 2012 @HCMUT 121 Form fields – core fields argument • required • label:
  • 122. 23/08/2012 Python - Django Training Course 2012 @HCMUT 122 Form fields – core fields argument • initial: • help_text: • Error_messages:
  • 123. 23/08/2012 Python - Django Training Course 2012 @HCMUT 123 Form 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
  • 124. 23/08/2012 Python - Django Training Course 2012 @HCMUT 124 ModelForms • Make form directly from models • Fields type conversion: see more at: https://docs.djangoproject.com/en/1.4/topics/forms/modelfo rms/#field-types
  • 125. 23/08/2012 Python - Django Training Course 2012 @HCMUT 125 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
  • 126. 23/08/2012 Python - Django Training Course 2012 @HCMUT 126 ModelForms – customize • Overriding the default field types or widgets:
  • 127. 23/08/2012 Python - Django Training Course 2012 @HCMUT 127 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.
  • 128. 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
  • 129. 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/
  • 130. 23/08/2012 Python - Django Training Course 2012 @HCMUT 130 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
  • 131. 23/08/2012 Python - Django Training Course 2012 @HCMUT 131 File Uploads • Conditions in templates to use: • enctype="multipart/form-data“ • method was POST
  • 132. 23/08/2012 Python - Django Training Course 2012 @HCMUT 132 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
  • 133. 23/08/2012 Python - Django Training Course 2012 @HCMUT 133 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)
  • 134. 23/08/2012 Python - Django Training Course 2012 @HCMUT 134 Outputting PDF • Install ReportLab: • Write your view
  • 135. 23/08/2012 Python - Django Training Course 2012 @HCMUT 135 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
  • 136. 23/08/2012 Python - Django Training Course 2012 @HCMUT 136 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
  • 137. 23/08/2012 Python - Django Training Course 2012 @HCMUT 137 Generic Views (cont.) • list_detail.object_list e.g
  • 138. 23/08/2012 Python - Django Training Course 2012 @HCMUT 138 Generic Views (cont.) • Other necessary fields:
  • 139. 23/08/2012 Python - Django Training Course 2012 @HCMUT 139 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
  • 140. 23/08/2012 Python - Django Training Course 2012 @HCMUT 140 Generic Views (cont.) • Other generic views should know: • Simple generic views • View • TemplateView • RedirectView • Detail views • DetailView • List views • ListView
  • 141. 23/08/2012 Python - Django Training Course 2012 @HCMUT 141 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,...
  • 142. 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
  • 143. 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/
  • 144. 23/08/2012 Python - Django Training Course 2012 @HCMUT 144 Other topics - Outcomes • Understand clearly and apply these information in your project, exercises.
  • 145. 23/08/2012 Python - Django Training Course 2012 @HCMUT 145 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.
  • 146. 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')
  • 147. 23/08/2012 Python - Django Training Course 2012 @HCMUT 147 User authentication (cont.) • Usage: • creating users: • changing password: • creating superuser:
  • 148. 23/08/2012 Python - Django Training Course 2012 @HCMUT 148 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:
  • 149. 23/08/2012 Python - Django Training Course 2012 @HCMUT 149 User authentication (cont.) • How to log a user in: • Authenticate() and login(): • logout():
  • 150. 23/08/2012 Python - Django Training Course 2012 @HCMUT 150 User 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:
  • 151. 23/08/2012 Python - Django Training Course 2012 @HCMUT 151 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, 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)
  • 152. 23/08/2012 Python - Django Training Course 2012 @HCMUT 152 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.
  • 153. 23/08/2012 Python - Django Training Course 2012 @HCMUT 153 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)
  • 154. 23/08/2012 Python - Django Training Course 2012 @HCMUT 154 Testing Django App. (cont.) • Running test:
  • 155. 23/08/2012 Python - Django Training Course 2012 @HCMUT 155 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:
  • 156. 23/08/2012 Python - Django Training Course 2012 @HCMUT 156 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
  • 157. 23/08/2012 Python - Django Training Course 2012 @HCMUT 157 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
  • 158. 23/08/2012 Python - Django Training Course 2012 @HCMUT 158 Sending 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)
  • 159. 23/08/2012 Python - Django Training Course 2012 @HCMUT 159 Sending Email (cont.) • Prevent Header injection: - handling email form
  • 160. 23/08/2012 Python - Django Training Course 2012 @HCMUT 160 Pagination • In views.py:
  • 161. 23/08/2012 Python - Django Training Course 2012 @HCMUT 161 Pagination (Cont.) • in templates (html files)
  • 162. 23/08/2012 Python - Django Training Course 2012 @HCMUT 162 Turn Debug mode off • in settings.py, you set TEMPLATE_DEBUG and DEBUG to False • write 404.html
  • 163. 23/08/2012 Python - Django Training Course 2012 @HCMUT 163 Turn Debug mode off (cont.) • And write 500.html template • Setting up Error alert:
  • 164. 23/08/2012 Python - Django Training Course 2012 @HCMUT 164 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.
  • 165. 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
  • 166. 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/
  • 167. 23/08/2012 Python - Django Training Course 2012 @HCMUT 167 PART 13 - DEPLOYMENT Time to attract people to your website
  • 168. 23/08/2012 Python - Django Training Course 2012 @HCMUT 168 Outline • Setup environment • Use Virtualenv • Deploy w/ Apache2 and Mod_WSGI • Serve static files
  • 169. 23/08/2012 Python - Django Training Course 2012 @HCMUT 169 SETUP ENVIRONMENT
  • 170. 23/08/2012 Python - Django Training Course 2012 @HCMUT 170 Prerequisites • Ubuntu (10.4 or newer) server or desktop • Apache2 • Virtualenv • Django 1.x and other libs on Virtualenv
  • 171. 23/08/2012 Python - Django Training Course 2012 @HCMUT 171 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
  • 172. 23/08/2012 Python - Django Training Course 2012 @HCMUT 172 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
  • 173. 23/08/2012 Python - Django Training Course 2012 @HCMUT 173 USE VIRTUALENV
  • 174. 23/08/2012 Python - Django Training Course 2012 @HCMUT 174 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.
  • 175. 23/08/2012 Python - Django Training Course 2012 @HCMUT 175 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.
  • 176. 23/08/2012 Python - Django Training Course 2012 @HCMUT 176 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
  • 177. 23/08/2012 Python - Django Training Course 2012 @HCMUT 177 DEPLOY W/ APACHE2 AND MOD_WSGI
  • 178. 23/08/2012 Python - Django Training Course 2012 @HCMUT 178 Components links to Apache Script WSGI Script links to Django Project Directory
  • 179. 23/08/2012 Python - Django Training Course 2012 @HCMUT 179 Apache 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>
  • 180. 23/08/2012 Python - Django Training Course 2012 @HCMUT 180 WSGI 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()
  • 181. 23/08/2012 Python - Django Training Course 2012 @HCMUT 181 Enable site • Enable Apache script > a2ensite myproject • Restart Apache server > sudo service apache2 restart
  • 182. 23/08/2012 Python - Django Training Course 2012 @HCMUT 182 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.
  • 183. 23/08/2012 Python - Django Training Course 2012 @HCMUT 183 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.
  • 184. 23/08/2012 Python - Django Training Course 2012 @HCMUT 184 Deployment - Exercises • Deploy your Django project with nginx (a different web server).
  • 185. 23/08/2012 Python - Django Training Course 2012 @HCMUT 185 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.
  • 186. 23/08/2012 Python - Django Training Course 2012 @HCMUT 186 Django Dev. Determine the functions of your website Process 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