Python - Django Training: BY: BKIT ATOM, Epsilon Mobile at HCMC HCMUT Summer 2012 Main Reference
Python - Django Training: BY: BKIT ATOM, Epsilon Mobile at HCMC HCMUT Summer 2012 Main Reference
TRAINING
BY: BKIT ATOM, Epsilon Mobile @ HCMC HCMUT
Summer 2012
Main reference:
https://docs.djangoproject.com/en/1.4/
Contact: [email protected]
23/08/2012 Python - Django Training Course 2012 @HCMUT 2
Instructors
• Nguyễn Đức Minh Khôi ([email protected])
• Phạm Trần Xuân Minh ([email protected])
• Võ Xuân Thịnh ([email protected])
• Trần Đăng Khoa ([email protected])
• Lê Trung Hiếu ([email protected])
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
• 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
Web components
23/08/2012 Python - Django Training Course 2012 @HCMUT 11
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
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
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
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:
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 (cont.)
• Model methods
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:
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()
QuerySet-Exercises1:
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- 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
• CREATING
+ Create 100 EMPLOYEEs
+ Create 20 PROJECTs
+ Create DEPARTMENTs: HR, IT, marketing, R & D,
23/08/2012 Python - Django Training Course 2012 @HCMUT 55
• 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
• InlineModelAdmin Object
• InlineModelAdmin Option
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
• If you are happy with the default admin interface, just use:
23/08/2012 Python - Django Training Course 2012 @HCMUT 62
ModelAdmin.list_display_links
ModelAdmin.list_editable
23/08/2012 Python - Django Training Course 2012 @HCMUT 67
• ModelAdmin.search_fields
23/08/2012 Python - Django Training Course 2012 @HCMUT 68
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
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
• include(<module or pattern_list>)
23/08/2012 Python - Django Training Course 2012 @HCMUT 85
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
• 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
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
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
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”)
Filters
• Use filters to modify variables for display
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 %}
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>
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))
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.
• 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
• {{ 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
• label:
23/08/2012 Python - Django Training Course 2012 @HCMUT 122
• help_text:
• Error_messages:
23/08/2012 Python - Django Training Course 2012 @HCMUT 123
ModelForms
• Make form directly from models
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
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
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:
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
• list_detail.object_list e.g
23/08/2012 Python - Django Training Course 2012 @HCMUT 138
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
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
• changing password:
• creating superuser:
23/08/2012 Python - Django Training Course 2012 @HCMUT 148
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
• logout():
23/08/2012 Python - Django Training Course 2012 @HCMUT 150
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 = '[email protected]'
• 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
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
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
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
Components
links to
Apache Script WSGI Script
links to
Django Project
Directory
23/08/2012 Python - Django Training Course 2012 @HCMUT 179
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
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