Django - basics


Published on

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Django - basics

  1. 1. Epsilon Mobile Pte. Ltd.PYTHON/DJANGO COURSE OUTLINECOURSE OBJECTIVESThe primary goal of this course is to provide you basic understandings and skills at Web programming. Youwill learn Python, Django, HTML/CSS languages and learn how to deploy your own website on a cloudserver. Not only knowledge but also practical experiences will be conveyed to you on your behalf.INSTRUCTORS AND CONTACT INFORMATION Tran Dang Khoa Vo Thanh Loc Lecturer Assistant Lecturer Email: Email: Tel: (+84) 935 667 311 Tel: (+84) 1674 575 320COURSE METHODOLOGYThis course includes lectures, exercises and a final project. This multiplicity of methods allows you to:1. Test your understandings of theories presented in readings.2. Use theories to solve the actual problems in organizations.3. Develop skills in programming, in presentation and in self-studying.This course occurs in a short duration, so the lecturer will guide you to focus on main topics. You also needto reserve your self-studying time to review theories, do exercises and do the final project from the middletime of this course.COURSE MATERIALS AND REFERENCESThe course slides prepared by Epsilon MobilePython Tutorial (Guido van Rossum) http://docs.python.orgDjango Official Documentation https://docs.djangoproject.comHTML Tutorial (WSC)
  2. 2. CSS Tutorial (WSC) SCHEDULEDuration: September 19th to October 14th, 2011Time: from 19:00 to 21:00, Monday – Wednesday – Friday each weekTotal sessions: 12 Session Topics 1 Python Programming Basics 2 Django Installation and Configuration 3 Models and QuerySets 4 URL Configuration and Request/Response 5 File Uploads and Generic Views 6 HTML and Django Template 7 CSS 8 Forms 9 Deployment under Linux platform (Ubuntu) 10 Admin sites 11 Advanced techniques and Q&A 12 Presentation of final projects
  3. 3. CREATE NEW PROJECT INDJANGO/PYTHON 1. Run: startproject project_name 2. Running the development server: python runserver 3. Open up and add these lines at the top: import os ROOT_PATH = os.path.dirname(__file__) PROJECT_DIR=os.path.dirname(__file__) a. If you want to use template folder to store html file, create new folder templates, and insert these code in TEMPLATE_DIRS = (os.path.join(PROJECT_DIR,"templates")) b. If you want to use static file (css, image, js,..) or media file(video, audio,..) create folder static and media in project folder and insert these code in in project folder: MEDIA_ROOT = os.path.join(PROJECT_DIR, /media/) MEDIA_URL = /media/ STATIC_ROOT = os.path.join(PROJECT_DIR, /static/) STATIC_URL = /static/ In the file: Insert code: from django.contrib.staticfiles.urls import staticfiles_urlpatterns at the beginning and code: urlpatterns += staticfiles_urlpatterns()at the end and add these line: url(r^media/(?P<path>.*)$, django.views.static.serve, {document_root: media}), c. If you want to add more information about users: • Declare in AUTH_PROFILE_MODULES = accounts.UserProfile • In create new class: UserProfile(models.Model): # additional information dob = models.DateField() # ... many as you wish User.profile = property(lambda u: PubProfile.objects.get_or_create(user=u)[0]) # (Tips) d. If you want to add email sending utility, add these lines in too: EMAIL_HOST = #if just test on localhost: = ‘localhost’
  4. 4. EMAIL_HOST_USER = EMAIL_HOST_PASSWORD = yourpass EMAIL_PORT = 587 # Check on the Internet if not successful #if just test #on localhost: = 1025 EMAIL_USER_TLS = True # Gmail now accepts HTTPS only e. If you want to use Admin feature, uncomment all line related to admin in INSTALLED_APP in and and re sync the database. Add these line to from django.contrib import admin admin.autodiscover()4. Syncing database: a. If not have user, create user in mysql: Login root account in cmd: mysql –u root –p and enter your password CREATE USER newUser@% IDENTIFIED BY password; mysql> GRANT ALL PRIVILEGES ON *.* TO newUser@% -> WITH GRANT OPTION; CREATE USER newUser@localhost IDENTIFIED BY password; mysql> GRANT ALL PRIVILEGES ON *.* TO newUser@localhost -> WITH GRANT OPTION; b. If not have database to connect, create new database: create database databaseName (just like in Oracle) c. Setup database engine through file5. If you want, create an App: python startapp appName a. Install your app above in INSTALLED_APPS = {… ‘projectName.appName’} b. If don’t have: create new . add from django.conf.urls.defaults import patterns, include, url at beginning and urlpatterns = patterns(, …) and Add url(r’^RegularExpressOfTheHTML/$’, include(name of the fuction)), to the of the project directory to show which function to be initialized when a specific url enter. c. Create for app if you want to add some models to you process by admin site: from django.contrib import admin from mkcomics.normalpage.models import *
  5. 5. d. Create for app: describe the database If you want to use table user: Add: from django import forms from django.db import models from django.contrib.auth.models import UserRun: python syncdb e. Interact with database: in the project’s folder, run the command line and run: python shell f. In your app, if you want to use form, create new file and at the beginning from django.forms import ModelForm from django.contrib.auth.models import User And add: from projectName.appName.models import * And add: from django import forms at begining g. In your app, at, implement your function in the //must have request parameter Add the beginning: add from ProjectName.appName.models import * form ProjectName.appName.forms import * from django.shortcuts import render_to_response, redirect from django.template.context import RequestContext from django.contrib.auth import login, authenticate from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.core.mail import send_mail, BadHeaderError h. Describe your HTML. You can use Django templates and Form to customize your HTML code. Remember to make block for inheritance as much as possible. Use CSS if you want. See your work: go to http://localhost:8000/ to check your projectMTV models in Django: View Model Template Business Logic Layer Data access Layer Presentation Layer
  6. 6. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.SESSION 1 – PYTHON PROGRAMMINGBASICSWhat is Python?Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Itshigh-level built in data structures, combined with dynamic typing and dynamic binding, make it veryattractive for Rapid Application Development, as well as for use as a scripting or glue language toconnect existing components together. Pythons simple, easy to learn syntax emphasizes readability andtherefore reduces the cost of program maintenance. Python supports modules and packages, whichencourages program modularity and code reuse.Installing PythonOfficial Website: http://www.python.orgRead installation guideline of your OS platform, download source or binary version for your OS and dosteps in the guideline.Interactive Mode ProgrammingBesides running a source file like other language, Python supports interactive mode programming whereyou can type code and invoking the interpreter immediately.Way 1 – Running Python interpreter from command-line1|Page
  7. 7. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.Way 2 – Running IDLE (Integrated DeveLopment Environment)Lines and IndentationThere are no braces to indicate block of code in Python. Python denotes blocks of code by lineindentation, which enforces very good format of code in practice. Therefore, make code easier tounderstand.Note: The number of spaces in indentation is VARIABLE, but all lines within a block MUST be indentedthe same amount. For example, the following code is fine:However, this will generate an error:2|Page
  8. 8. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.Multi-line StatementsPython uses the line continuation character () to denote that the line should continue:However, statements within the [], {}, or () brackets do not need to use line continuation character:Comments in PythonStandard Data TypesThere are 5 standard types:  Numbers: support int, long, float and complex.3|Page
  9. 9. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.  String: a contiguous set of characters in between quotation marks.  List: a container that holds a number of other objects, even list objects.  Tuple: similar to list but enclosed within parenthese. It is also thought as a read-only list.  Dictionary: consists of key-value pairs.4|Page
  10. 10. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.Condition StatementsCombine if, elif and else statementsLoop StatementsFlow-control statements  break: terminates the current loop and resumes execution at the next statement.  continue: returns the control to the beginning of the loop.  pass: executes nothing (null operation), used as a placeholder of future code.5|Page
  11. 11. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.FunctionFor example:ModulesA module allows you to logically organize the Python code by grouping related code into a module tomake the code more understandable and reusable.Import a moduleYou can use import statement to utilize code of a module. When the interpreter encounters an importstatement, it will attempt to import the module in the search path.Organize a standard module - Make a new folder which name will be your module name. - Create a blank file, name it (reference more in Python documentation). - Add your source files (*.py) into this folder. - Append your module folder path to PYTHONPATH.6|Page
  12. 12. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.Handling exceptions If you have some suspicious code that may raise an exception, place the code in a try: block and except:statement and finally: statement (optional).ClassFormat of a ClassClass InheritanceDeriving from a base class, the child class inherits all the attributes and can also override data membersand methods from the parent.7|Page
  13. 13. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.Exercises1. 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 from1 to 100. After that, the program will ask the user for a guess number. If the guess number is greaterthan the lucky number, it will print out “Too high”; if the guess number is less than the lucky number, itwill print out “Too low”. The program will continue to ask a new guess number until the user enters thelucky number. As a consequence, it will print out “You guess right! It costs you x guesses”, where x is thenumber of guesses the user tries.3. Write a dictionary program (use Dictionary type). When launching, the users can choose 3 optionsfrom the main menu:a. Search a wordb. Import dictionaryc. Exit- If the user chooses Search a word, it will require him to enter a word, then, it will print out thedefinition 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 mainmenu.- If the user chooses Exit, the program will terminate immediately.The dictionary file is a plain text file with the following format: word1 definition1 word2 definition2 …8|Page
  14. 14. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.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 studentsb. Add new studentc. Remove a studentd. 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.5. (Plus) Write a mini text-chat (client/server) by using Python networking modules.Hint: Read Python documentation and use Google to find the necessary modules for your answers.RequirementSubmit your answers for exercises before 00:00 AM on Wednesday, September 21st, 2011 at:khoatran@epsilon-mobile.com9|Page
  15. 15. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.SESSION 2 – Django Installation andConfigurationOverviewIn order to develop website using Python/Django framework, we currently need to install the followingpackages:1. Python 2.7.x2. Django 1.x.x3. MySQL 5.x4. Python Setuptools5. MySQL-python-1.2.3Installing Python 2.7.xGo to the official hompage at and see the guidelineInstalling Django 1.x.x- Go to Download Django-1.x.x.tar.gz- Unzip the downloaded file- Open command-line at folder Django-1.x.x- Run Installing MySQL 5.x- Go to Install MySQL Community Server (recommend version 5.1.x for Windows 7)- Install MySQL WorkbenchInstalling Python Setuptools- Go to Download your appropriate package (depends on OS). For example, in Windows, we can choose MSWindows Installer version with the corresponding python version.1|Page
  16. 16. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.- Install the downloaded file. If in debian Linux, you can use .Installing MySQL-python-1.2.3- Download MySQL-python at Unzip the download file- Open command-line at folder MySQL-python-1.2.3- Run Note: In Windows, you should download the binary version to install more easily( a Django project- Make sure that Django bin folder appended into PATH.- Run - Django Admin Utility will create an empty project structure automatically for you.  An empty file that tells Python that this directory should be considered a Python package.  A command-line utility that lets you interact with this Django project in various ways.  Settings/configuration for this Django project.  The URL declarations for this Django project; a "table of contents" of your Django- powered site.Running the development server- At the root directory of the project, run python runserver.- The development server will be started at (default). You can change the address byspecifying IP:Port at the end of the above command.- Open in your web browser. You will go to Django-powered default page.2|Page
  17. 17. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.Workshop: Student Management SystemThis system allows users to add new student information and explore it again.Creating an AppAn app is a Web application that does something -- e.g., a Weblog system, a database of public recordsor a simple poll app. A project is a collection of configuration and apps for a particular Web site. Aproject can contain multiple apps. An app can be in multiple projects.To create an App, use utility with startapp command.Creating modelsModel in Django is an object-relational mapper in which you describe your database layout in Pythoncode.3|Page
  18. 18. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.Syncing database- Create database named mysite in MySQL.- Setup database engine in Install app in|Page
  19. 19. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.- Run - Review MySQL tables to understand this mechanism.Configuring URLs- In at root directory5|Page
  20. 20. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.- Create new inside sms app folderWriting your views- In of sms app- sms/explore.html is a HTML and Django-syntax template6|Page
  21. 21. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.Writing a templateExercises1. Complete the Adding Student feature.RequirementSubmit your answers for exercises before 00:00 AM on Friday, September 23rd, 2011 at:khoatran@epsilon-mobile.com7|Page
  22. 22. Database SQL Python Your apps Django Behind the scenes • You can use Python – sql statement for insert, update, and delete action: • If the filter statement isn’t powerful enough, use raw SQL statement Python – sql equivalent:command Python sqlInsertinto Or p = Publisher.objects.create()
  23. 23. Select *fromSelect …whereSelect …order bySelect …where…order bySelect …where …order by… offsetlimitexclude p = Publisher.objects.exclude(name = “O’Reilly”)update Return an object, usually with try, catch: try: get() catch(Exception): pass if have many rows, throws Duplicate Exception The condition in get() can use the Field lookup!DeleteAverage,
  24. 24. … just likefunctionin SQL Field lookups Field lookups are how you specify the meat of an SQL WHERE clause. Theyre specified as keyword arguments to the QuerySet methods filter(), exclude() and get(). For an introduction, see models and database queries documentation. exact Exact match. If the value provided for comparison is None, it will be interpreted as an SQL NULL (see isnull for more details). Examples: Entry.objects.get(id__exact=14) Entry.objects.get(id__exact=None) SQL equivalents: SELECT ... WHERE id = 14; SELECT ... WHERE id IS NULL; MySQL comparisons In MySQL, a database tables "collation" setting determines whether exact comparisons are case-sensitive. This is a database setting, not a Django setting. Its possible to configure your MySQL tables to use case-sensitive comparisons, but some trade-offs are involved. For more information about this, see the collation section in thedatabases documentation. iexact
  25. 25. Case-insensitive exact match.Example:Blog.objects.get(name__iexact=beatles blog)SQL equivalent:SELECT ... WHERE name ILIKE beatles blog;Note this will match Beatles Blog, beatles blog, BeAtLes BLoG, etc.SQLite usersWhen using the SQLite backend and Unicode (non-ASCII) strings, bear in mind the database note about string comparisons. SQLite does notdo case-insensitive matching for Unicode strings.containsCase-sensitive containment test.Example:Entry.objects.get(headline__contains=Lennon)SQL equivalent:SELECT ... WHERE headline LIKE %Lennon%;Note this will match the headline Lennon honored today but not lennon honored today.SQLite users
  26. 26. SQLite doesnt support case-sensitive LIKE statements; contains acts like icontains for SQLite. See thedatabase note for moreinformation.icontainsCase-insensitive containment test.Example:Entry.objects.get(headline__icontains=Lennon)SQL equivalent:SELECT ... WHERE headline ILIKE %Lennon%;SQLite usersWhen using the SQLite backend and Unicode (non-ASCII) strings, bear in mind the database note about string comparisons.inIn a given list.Example:Entry.objects.filter(id__in=[1, 3, 4])SQL equivalent:SELECT ... WHERE id IN (1, 3, 4);You can also use a queryset to dynamically evaluate the list of values instead of providing a list of literal values:inner_qs = Blog.objects.filter(name__contains=Cheddar)
  27. 27. entries = Entry.objects.filter(blog__in=inner_qs)This queryset will be evaluated as subselect statement:SELECT ... WHERE IN (SELECT id FROM ... WHERE NAME LIKE %Cheddar%)The above code fragment could also be written as follows:inner_q = Blog.objects.filter(name__contains=Cheddar).values(pk).queryentries = Entry.objects.filter(blog__in=inner_q)This second form is a bit less readable and unnatural to write, since it accesses the internal query attribute and requires aValuesQuerySet.If your code doesnt require compatibility with Django 1.0, use the first form, passing in a queryset directly.If you pass in a ValuesQuerySet or ValuesListQuerySet (the result of calling values() or values_list() on a queryset) as thevalue to an __in lookup, you need to ensure you are only extracting one field in the result. For example, this will work (filtering on the blognames):inner_qs = Blog.objects.filter(name__contains=Ch).values(name)entries = Entry.objects.filter(blog__name__in=inner_qs)This example will raise an exception, since the inner query is trying to extract two field values, where only one is expected:# Bad code! Will raise a TypeError.inner_qs = Blog.objects.filter(name__contains=Ch).values(name, id)entries = Entry.objects.filter(blog__name__in=inner_qs)Warning
  28. 28. This query attribute should be considered an opaque internal attribute. Its fine to use it like above, but its API may change between Djangoversions.Performance considerationsBe cautious about using nested queries and understand your database servers performance characteristics (if in doubt, benchmark!). Somedatabase backends, most notably MySQL, dont optimize nested queries very well. It is more efficient, in those cases, to extract a list ofvalues and then pass that into the second query. That is, execute two queries instead of one:values = Blog.objects.filter( name__contains=Cheddar).values_list(pk, flat=True)entries = Entry.objects.filter(blog__in=list(values))Note the list() call around the Blog QuerySet to force execution of the first query. Without it, a nested query would be executed,because QuerySets are lazy.gtGreater than.Example:Entry.objects.filter(id__gt=4)SQL equivalent:SELECT ... WHERE id > 4;gteGreater than or equal to.
  29. 29. ltLess than.lteLess than or equal to.startswithCase-sensitive starts-with.Example:Entry.objects.filter(headline__startswith=Will)SQL equivalent:SELECT ... WHERE headline LIKE Will%;SQLite doesnt support case-sensitive LIKE statements; startswith acts like istartswith for SQLite.istartswithCase-insensitive starts-with.Example:Entry.objects.filter(headline__istartswith=will)SQL equivalent:SELECT ... WHERE headline ILIKE Will%;SQLite users
  30. 30. When using the SQLite backend and Unicode (non-ASCII) strings, bear in mind the database note about string comparisons.endswithCase-sensitive ends-with.Example:Entry.objects.filter(headline__endswith=cats)SQL equivalent:SELECT ... WHERE headline LIKE %cats;SQLite usersSQLite doesnt support case-sensitive LIKE statements; endswith acts like iendswith for SQLite. Refer to thedatabase note documentationfor more.iendswithCase-insensitive ends-with.Example:Entry.objects.filter(headline__iendswith=will)SQL equivalent:SELECT ... WHERE headline ILIKE %willSQLite usersWhen using the SQLite backend and Unicode (non-ASCII) strings, bear in mind the database note about string comparisons.
  31. 31. rangeRange test (inclusive).Example:start_date =, 1, 1)end_date =, 3, 31)Entry.objects.filter(pub_date__range=(start_date, end_date))SQL equivalent:SELECT ... WHERE pub_date BETWEEN 2005-01-01 and 2005-03-31;You can use range anywhere you can use BETWEEN in SQL — for dates, numbers and even characters.yearFor date/datetime fields, exact year match. Takes a four-digit year.Example:Entry.objects.filter(pub_date__year=2005)SQL equivalent:SELECT ... WHERE pub_date BETWEEN 2005-01-01 AND 2005-12-3123:59:59.999999;(The exact SQL syntax varies for each database engine.)month
  32. 32. For date and datetime fields, an exact month match. Takes an integer 1 (January) through 12 (December).Example:Entry.objects.filter(pub_date__month=12)SQL equivalent:SELECT ... WHERE EXTRACT(month FROM pub_date) = 12;(The exact SQL syntax varies for each database engine.)dayFor date and datetime fields, an exact day match.Example:Entry.objects.filter(pub_date__day=3)SQL equivalent:SELECT ... WHERE EXTRACT(day FROM pub_date) = 3;(The exact SQL syntax varies for each database engine.)Note this will match any record with a pub_date on the third day of the month, such as January 3, July 3, etc.week_dayFor date and datetime fields, a day of the week match.Takes an integer value representing the day of week from 1 (Sunday) to 7 (Saturday).Example:
  33. 33. Entry.objects.filter(pub_date__week_day=2)(No equivalent SQL code fragment is included for this lookup because implementation of the relevant query varies among different databaseengines.)Note this will match any record with a pub_date that falls on a Monday (day 2 of the week), regardless of the month or year in which itoccurs. Week days are indexed with day 1 being Sunday and day 7 being Saturday.isnullTakes either True or False, which correspond to SQL queries of IS NULL and IS NOT NULL, respectively.Example:Entry.objects.filter(pub_date__isnull=True)SQL equivalent:SELECT ... WHERE pub_date IS NULL;searchA boolean full-text search, taking advantage of full-text indexing. This is like contains but is significantly faster due to full-text indexing.Example:Entry.objects.filter(headline__search="+Django -jazz Python")SQL equivalent:SELECT ... WHERE MATCH(tablename, headline) AGAINST (+Django -jazz Python INBOOLEAN MODE);
  34. 34. Note this is only available in MySQL and requires direct manipulation of the database to add the full-text index. By default Django usesBOOLEAN MODE for full text searches. See the MySQL documentation for additional details.regexCase-sensitive regular expression match.The regular expression syntax is that of the database backend in use. In the case of SQLite, which has no built in regular expression support,this feature is provided by a (Python) user-defined REGEXP function, and the regular expression syntax is therefore that ofPythons re module.Example:Entry.objects.get(title__regex=r^(An?|The) +)SQL equivalents:SELECT ... WHERE title REGEXP BINARY ^(An?|The) +; -- MySQLSELECT ... WHERE REGEXP_LIKE(title, ^(an?|the) +, c); -- OracleSELECT ... WHERE title ~ ^(An?|The) +; -- PostgreSQLSELECT ... WHERE title REGEXP ^(An?|The) +; -- SQLiteUsing raw strings (e.g., rfoo instead of foo) for passing in the regular expression syntax is recommended.iregex
  35. 35. Case-insensitive regular expression match.Example:Entry.objects.get(title__iregex=r^(an?|the) +)SQL equivalents:SELECT ... WHERE title REGEXP ^(an?|the) +; -- MySQLSELECT ... WHERE REGEXP_LIKE(title, ^(an?|the) +, i); -- OracleSELECT ... WHERE title ~* ^(an?|the) +; -- PostgreSQLSELECT ... WHERE title REGEXP (?i)^(an?|the) +; -- SQLitePerforming raw queriesNew in Django 1.2: Please, see the release notesThe raw() manager method can be used to perform raw SQL queries that return model instances:Manager.raw(raw_query, params=None, translations=None)This method method takes a raw SQL query, executes it, and returns a RawQuerySet instance. This RawQuerySet instance can be iteratedover just like an normal QuerySet to provide object instances.
  36. 36. This is best illustrated with an example. Suppose you’ve got the following model:class Person(models.Model): first_name = models.CharField(...) last_name = models.CharField(...) birth_date = models.DateField(...)You could then execute custom SQL like so:>>> for p in Person.objects.raw(SELECT * FROM myapp_person):... print pJohn SmithJane JonesOf course, this example isnt very exciting -- its exactly the same as running Person.objects.all(). However, raw() has a bunch ofother options that make it very powerful.Model table namesWhered the name of the Person table come from in that example?By default, Django figures out a database table name by joining the models "app label" -- the name you used startapp -- tothe models class name, with an underscore between them. In the example weve assumed that the Person model lives in an appnamed myapp, so its table would be myapp_person.For more details check out the documentation for the db_table option, which also lets you manually set the database table name.Warning
  37. 37. No checking is done on the SQL statement that is passed in to .raw(). Django expects that the statement will return a set of rows from thedatabase, but does nothing to enforce that. If the query does not return rows, a (possibly cryptic) error will result.Mapping query fields to model fieldsraw() automatically maps fields in the query to fields on the model.The order of fields in your query doesnt matter. In other words, both of the following queries work identically:>>> Person.objects.raw(SELECT id, first_name, last_name, birth_date FROMmyapp_person)...>>> Person.objects.raw(SELECT last_name, birth_date, first_name, id FROMmyapp_person)...Matching is done by name. This means that you can use SQLs AS clauses to map fields in the query to model fields. So if you had some othertable that had Person data in it, you could easily map it into Person instances:>>> Person.objects.raw(SELECT first AS first_name,... last AS last_name,... bd AS birth_date,... pk as id,... FROM some_other_table)As long as the names match, the model instances will be created correctly.
  38. 38. Alternatively, you can map fields in the query to model fields using the translations argument to raw(). This is a dictionary mappingnames of fields in the query to names of fields on the model. For example, the above query could also be written:>>> name_map = {first: first_name, last: last_name, bd: birth_date,pk: id}>>> Person.objects.raw(SELECT * FROM some_other_table, translations=name_map)Index lookupsraw() supports indexing, so if you need only the first result you can write:>>> first_person = Person.objects.raw(SELECT * from myapp_person)[0]However, the indexing and slicing are not performed at the database level. If you have a big amount of Person objects in your database, it ismore efficient to limit the query at the SQL level:>>> first_person = Person.objects.raw(SELECT * from myapp_person LIMIT 1)[0]Deferring model fieldsFields may also be left out:>>> people = Person.objects.raw(SELECT id, first_name FROM myapp_person)The Person objects returned by this query will be deferred model instances (see defer()). This means that the fields that are omitted fromthe query will be loaded on demand. For example:>>> for p in Person.objects.raw(SELECT id, first_name FROM myapp_person):... print p.first_name, # This will be retrieved by the original query
  39. 39. ... print p.last_name # This will be retrieved on demand...John SmithJane JonesFrom outward appearances, this looks like the query has retrieved both the first name and last name. However, this example actually issued3 queries. Only the first names were retrieved by the raw() query -- the last names were both retrieved on demand when they were printed.There is only one field that you cant leave out - the primary key field. Django uses the primary key to identify model instances, so it mustalways be included in a raw query. An InvalidQuery exception will be raised if you forget to include the primary key.Adding annotationsYou can also execute queries containing fields that arent defined on the model. For example, we could use PostgreSQLs age() function to geta list of people with their ages calculated by the database:>>> people = Person.objects.raw(SELECT *, age(birth_date) AS age FROMmyapp_person)>>> for p in people:... print "%s is %s." % (p.first_name, p.age)John is 37.Jane is 42....Passing parameters into raw()
  40. 40. If you need to perform parameterized queries, you can use the params argument to raw():>>> lname = Doe>>> Person.objects.raw(SELECT * FROM myapp_person WHERE last_name = %s,[lname])params is a list of parameters. Youll use %s placeholders in the query string (regardless of your database engine); theyll be replaced withparameters from the params list.WarningDo not use string formatting on raw queries!Its tempting to write the above query as:>>> query = SELECT * FROM myapp_person WHERE last_name = %s % lname>>> Person.objects.raw(query)Dont.Using the params list completely protects you from SQL injection attacks, a common exploit where attackers inject arbitrary SQL into yourdatabase. If you use string interpolation, sooner or later youll fall victim to SQL injection. As long as you remember to always usethe params list youll be protected.
  41. 41. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.SESSION 4 – URL Configuration andHttpRequest/HttpResponseURL ConfigurationURLConf is a module that maps between URL patterns to Python view functions. Regularly, you defineURL patterns in of a Project or each App.Example of URL patternsYou should know: - In Python, r’’ is a raw string. It denotes that this string should not be escaped. - The URL patterns are in Regex format. You can reference at, however, you should not focus on it now. - Caret sign (^) denotes the beginning of a pattern. - Dollar sign ($) denotes the end of a pattern. This is the reason that when including URL patterns of an App, you do not put $ at the end because it still continues to match: - ?P<param_name> is to define named group. After matching, the URL parameter will be passed to view function’s parameter: The view’s parameter MUST be the same with the URL parameter, e.g. movie_id. - d+ is to match a string (continuous characters) which contains digits only, i.e. 0,1,2… 9Some useful patternsThe following patterns are used in almost usual cases. You can find more patterns from the Internet(Python Regex) or master Regex to create on your own.1|Page
  42. 42. Python/Django Course 2011 Epsilon Mobile Pte. Ltd. - d{n}: n is an integer number which indicates how many characters in this digit string. For example, d{4} will match 0123 but not match 123. - d+: a digit string with no limit characters. - w{n} and w+: the same but matches strings with alphabetical and digit and underscore characters. - [a-z]{n} and [a-z]+: accepts a-z characters only. - [a-zA-Z0-9]+: like what you think of :D. - [-wd]{36}: matches for uuid.uuid1.url() functionUse this wrapper function if you want to define name for an URL. You can use this name in template filesthrough url template tag like the following example:You can also pass URL parameters in url template tag (Hint: used to construct links for exploring a moviein the example). See the documentation for more details.include() functionYou have used it already so I do not need to explain it again ^^.HttpRequest and HttpResponseWhen the client requests to Web server at the URL, it will pass the request parameter to thecorresponding view function. This parameter is HttpRequest response.Each view function has to return an HttpResponse object. Django will use the object to return the clientHTML (or other formats).The documentation is clear and informative enough. The following points are what you should to focus:2|Page
  43. 43. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.HttpRequest:, GET, POST, user, raw_post_data, read().HttpResponse:,HttpResponse subclasses.Shortcuts:, render_to_string, redirect.Exercises 1. Reconstruct the URL patterns of your Session 3 exercises. You have to use URL parameters to shorten your patterns. 2. Feature: Add new movie by submitting an XML file (write a small page for submitting file) For director, actor and category, if name does not exist, it will create a new row in database. Otherwise, it will find the existing row to assign to the movie object. Hint: Read the first example of File Uploading; use ElementTree lib to parse XML file ( your answers for exercise 1 before 12:00 PM on Friday, September 30th, 2011 atkhoatran@epsilon-mobile.comSubmit your answers for exercise 2 before 00:00 AM on Monday, October 3rd, 2011 atkhoatran@epsilon-mobile.com3|Page
  44. 44. Session 6: Django Template SystemReview class: read • File Upload: Overview | File Objects | Managing File • Generic views: Overview | Built-in generic views • CSS: coi het den phan CSS Advanced AlignLearningVariable: {{}} {{student.get_average 1 2}} #1, 2 tham so truyen vaoFilter: -> co cac built in ngoai ra co the viet them vao | upper aBC ABC cac ham thuong dung: upper lower truncate_word escape -> mac dinh se escape het lengthTag: -> co cac built in ngoai ra co the viet them vao if if else if equal for
  45. 45. comment {# #}Inheritance Base.html <div> {% block content%} {%endblock content%} </div> Movie.html <div> {% extends block %} </div> #first template in child template {% block content of the movie.html (specific) %} Other: user {{block.super}}Other: Python dumpdata > data.json # xuat data ra file loaddata < data.json #nhap data tu file flush #xoa data hoan toan Muon luu cac file tinh nhu: image, css,… trong STATIC_ROOT trong setting.pyExercise:Redesign the movie website look like this: MOVIE DATABASE MOVIES DIRECTOR ACTOR CATEGORY COPYRIGHT
  46. 46. Tab: dung<ul style = “display:inline”> <li>Movie </li></ul>
  47. 47. SESSION 8: FORMOverview: 1. If form is huge: you can make new file to store themElse: include it in models.pyLookup more built-in field form: 2. Using form in a view: 3. Processing data with Form: 4. Displaying a form using a template: form.as_p will output the form with each form field and accompanying label wrapped in a paragraph. Heres the output for our example template:
  48. 48. You can also use form.as_table to output table rows (youll need to provide your own <table> tags) and form.as_ul to output list items.ModelForm 1. Syntax: 2. Model field and model form equivalent: 3. Other works just as normal form: but instead of processing with form.cleaned_data, just use for short 4. Notices: a. Using subsets of field in the form:
  49. 49. 1. Use the fields attribute of the ModelForms inner Meta class. This attribute, if given, should be a list of field names to include in the form. The order in which the fields names are specified in that list is respected when the form renders them. 2. Use the exclude attribute of the ModelForms inner Meta class. This attribute, if given, should be a list of field names to exclude from the form. b. Overriding default fields or widget: c. Changing order of fields: d. Form inheritance:Homework: Chuyen het sang form cho movie, director, actor ve add, edit
  50. 50. THEORY1. Understand User model.There are many fields in this model but you need to focus on 3 ones: username (unique), email (unique,optional) and password (hashed).Django does not store raw password, which you enter to login, but hashed string of the password. Whenusers submit their password, it will also be hashed and matched with the hashed password in database.This mechanism ensures that no one can get password of users when controlling access to database. Asyou know, many people use the same password with many different accounts so this is absolutely useful.To create a User instance, you should use User.objects.create_user(username, password, email).Parameter ``password`` in this function is the raw password. If you use User(username, password,email), the password you have to pass is the hashed one, very disturbing.To set/check password, similarly you should use its utility functions instead of assigningdirectly: set_password(password),check_password(password).2. How to use User in viewThere are 3 utility functions in django.contrib.auth:authenticate(username, password)login(request, user)logout(request)authenticate() is for checking username and password matching. If username does not exist or passworddoes not match, it will return None. Otherwise, it returns a User instance corresponding to who you wantto check. login() and logout() is easy to understand.I explain a bit about Django authentication system. login() function will append to request a HTTPCOOKIE parameter session_id. This session_id will be used to identify which user is working with theWeb server (because HTTP is stateless). Each HTTP request will send session_id belong. You canwatch session_id (COOKIE) by using Firebug on Firefox or Developer Tools on Chrome.There are 2 ways to force that only logged-in user can access the view:RAW WAYdef view(request); if request.user.is_authenticated(): pass # do something else: pass # return an error view or redirect to login view, for exampleDECORATOR@login_required()def view(request): passWhen using decorator, if the user has not logged in yet, it will be redirected to login page (LOGIN_URL, default is /account/login/)
  51. 51. 3. Extending User informationYou can extend the information fields for a user such as date of birth, address, habits, etc. by usingAuthentication Profile. There are 3 steps:- Declare in AUTH_PROFILE_MODULES = accounts.UserProfile+ accounts is an example app+ UserProfile (you can name it whatever you want) is your own Model class. For example:class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) # this is compulsory # additional information dob = models.DateField() # ... many as you wishUser.profile = property(lambda u: PubProfile.objects.get_or_create(user=u)[0]) # (Tips)Then you can access UserProfile instance by calling the instance method of User model: get_profile()(Tips): This line is optional but extremely useful. You can access UserProfile just like a field in a Modelinstance. For example: user.profile.dob = instead of user.get_profile().dob Moreover, you need to understand that when calling get_profile() or profile(property), it will query from SQL database. You should care about overhead:profile = user.get_profile() # 1 queryprofile.dob = = abc----> COST 1 QUERYInstead of:user.get_profile().dob = # 1 queryuser.get_profile().address = abc # 1 query----> COST 2 QUERIES4. Email Sending tips Do research by yourself first before reading this tip)a. Testing on localhost:- In = localhostEMAIL_PORT = 1025- Open a command-line: python -m smtpd -n -c DebuggingServer localhost:1025b. Sending email with your Gmail account- In = = abc@gmail.comEMAIL_HOST_PASSWORD = yourpassEMAIL_PORT = 587 # Check on the Internet if not successfulEMAIL_USER_TLS = True # Gmail now accepts HTTPS only
  52. 52. EXERCISES1. Create register/login page with additional information (DOB, Habits, Address, Country, etc.) for MovieDatabase. Only registered user can access it.2. Do research about Email Sending to implement this feature: Send a list of Actors or Directors or Moviesto users email.Lam viec truc tiep tren template (co built in san) va views thoi ( nho import vao)Flow (ve hinh)> thiet ke app > URLs (nen viet ro) > model > views > template(static nen de ngoai project thu muc luon)
  53. 53. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.SESSION 10 – The Admin SiteSetup the Admin SiteDjango framework comes up with its auto-generated CMS (Content Management System). It isextremely useful and help us to reduce development time.To use the Admin Site, you need to do the following steps: 1. Uncomment ‘django.contrib.admin’ in INSTALLED_APPS ( 2. Make sure that django.contrib.auth, django.contrib.contenttypes, django.contrib.messages and django.contrib.sessions is installed. Those are its dependencies. 3. Uncomment admin pattern in admin.autodiscover() function will traverse all app directories to find each file (optional for an app). You will be learnt what to declare in in the next section. 4. Finally, you need to sync the database again to install admin app. 5. Start the server and go to the Admin Site at Login with your super user account which is recommended to create when syncing database at the first time. If you haven’t created super user account yet, you can do it by using shell.1|Page
  54. 54. Python/Django Course 2011 Epsilon Mobile Pte. Ltd. With the default Admin Site, you can modify Users, Groups and Sites model instances. Add new Users and Groups by yourself to examine features of the Admin Site.Add new Model to the Admin SiteJust like Users or Groups model, you can add your own Models to be managed by the Admin Site: 1. Create file inside your app folder which contains Models (in you want to register with the Admin Site. 2. Register a Model by using This is a quick way to do that, for more advance settings see the next section. 3. Login into the Admin Site again to see the changes.2|Page
  55. 55. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.Customize InterfaceYou can customize the interface of the Admin Site by declaring your own ModelAdmin objects. Let’sexamine the following example: 1. If registering Model with default options, the interface of Adding page is like below: 2. I want to divide the information into 2 different groups: Basic Information and Advanced Information.3|Page
  56. 56. Python/Django Course 2011 Epsilon Mobile Pte. Ltd. 3. This is the code to achieve the new interface:For more options of ModelAdmin, please reference at|Page
  57. 57. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.Admin ActionsIn some cases, you need to achieve more complicated actions than only add/remove/change Modelinstances. It is when you want to write Admin Actions. For example, you want a feature that change allselected Movies to 21 recommended age viewer: 1. First, write your Action function in ModelAdmin subclass your_action(self, request, queryset) queryset is selected instances and request is HttpRequest (same with view function). 2. Declare attribute actions of ModelAdmin actions = [‘your_action’] 3. This is the total code 4. Go to the Admin Site and examine the changes After selecting instances and action, you need to click Go button to process it.5|Page
  58. 58. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.SESSION 11 – DeploymentIn order to deploy your Django website, you need to install and setup the following packages: - Python 2.x - Django 1.2.x - Apache2 and lib mod_wsgiEnvironment: Ubuntu 10.10Install python> sudo apt-get install python python-dev python-setuptools build-essentialInstall pip> sudo easy_install –U pipInstall Django> sudo pip install DjangoInstall Apache2 and mod_wsgi> sudo apt-get install apache2 libapache2-mod-wsgiTest mod_wsgiWrite WSGI Script> sudo mkdir /srv/www> sudo mkdir /srv/www/wsgi> sudo nano /srv/www/wsgi/app.wsgi1|Page
  59. 59. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.Write Apache Configuration Script> sudo nano /etc/apache2/sites-available/testEnable site:> sudo a2ensite testReload apache2 service:> sudo service apache2 reloadConfig host nameThis is for testing purpose on local only. In practice, you need to configure DNS settings for your owndomain (you will need to purchase one, e.g.> sudo nano /etc/hostsPrepend this line in hosts file: wsgi.djangoserverThe reason for this setting is, when you go to http://wsgi.djangoserver in Web browser, the request willbe resolved at (localhost) and match with VirtualHost configuration.TESTING DJANGO> cd /srv/www/> sudo startproject hello> sudo mkdir /srv/www/hello/apache> sudo nano /srv/www/hello/apache/django.wsgi2|Page
  60. 60. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.Your Apache configuration script is like below:After done, test your deployed site at http://hello.djangoserver/TIP 1: If we modify the code in Django project then rather than restarting apache we can just touch thewsgi file and the changes will be picked up:> sudo touch /srv/www/hello/apache/django.wsgiTIP 2: Even when your website has been deployed, you still can test in development mode:> python runserver 0:8080It will have the same effect with the deployed site if you use the same, more exactly point tothe same database. Access the development site at http://hello.djangoserver:8080/In-class Exercises 1. Deploy your Movie Database website so that everyone who joins the Wi-fi network epsilon_mobile can access it.3|Page
  61. 61. Python/Django Course 2011 Epsilon Mobile Pte. Ltd. Go to the Admin Site of your website in deployment mode. Does it display correctly with image/css/javascript? If not, try to fix it by yourself (Hint: Google). 2. Deploy your site with nginx server. Nginx is a light-weight FastCGI-support Web server, it is most effective when being used to serve static files. Reference: ubuntu-with-nginx-fastcgi-and-mysql/ (You only need to read from Installing nginx)ReminderYour final project should be presented at the deployment mode. The reason is that you might face sometroubles to make it run smoothly in practice. This is a good experience.4|Page
  62. 62. Python/Django Course 2011 Epsilon Mobile Pte. Ltd.Final AssignmentInstructionTo confirm your effective learning, you are required to complete a final assignment to experience allknowledge and techniques taught at this course. You are provided 2 topics, however, you can alsocreate your own ideas, then, submit them to our instructors to approve. Instructors take a responsibilityto ensure that your own topic matches what you need to achieve after this course.You need to submit your code by 00:00 AM on October 17th, 2011.The presentation of your assignment will be hold at 07:00 PM on October 19th, 2011.TOPIC 1: Social NetworkUser StoryAs a user, I can register my account at the Website. After registering, I can sign in to my homepage. Atmy homepage, I prefer to share my own ideas, pictures of my fantastic trips to all my friends. Ah, aboutfriends, I can make friends with anyone who has an account, hence, inviting friends by email is what Iwill try to do.RequirementYou need to complete the following features: - Register an account - Change account information - Add/Remove friends (relationship) - (login-required) - Post a sharing which can be in texts and pictures - Invite friends to join the network by emailTOPIC 2: Comic Online StoreUser StoryI need to have an account to read comics. There are many comic series and each one contains multipleissues. To access an issue, I have to purchase it or subscribe the series that this issue belongs to. Whenreading an issue, I can move between pages, zoom a page and bookmark page so that I can revisit fornext reading.RequirementYou need to complete the following features:1|Page
  63. 63. Python/Django Course 2011 Epsilon Mobile Pte. Ltd. - Register a Reader account - Show a Comic Series page which contains a list of issues - Manage (Add/Remove/Change) Comic Series, Comic Issues, etc. (Admin page) - Purchase an issue (e.g. 0.99$, 1.99$, etc.) - Subscribe a series (e.g. 99$) - Read a comic issue: Move between comic pages, zoom a page - Bookmark page is a plus2|Page