Presenter: Raman Prasad
Abstract: Creating custom data models (similar to "content types" in Drupal) can quickly become complicated. Data that looks like it will fit into 1 database table might actually need 4 tables--or 34. Django, a python based web framework, excels as a method of creating relational database tables, providing comprehensive administrative pages for users, and pulling the data out again in a variety of formats.
Django may be used for large systems, but it's also suitable for small projects. This presentation will cover very basic Django models in the context of moving office data from spreadsheets to online databases.
6. Django: Scalable (without magic and superclouds)
Firefox‟s Add-Ons Site Commenting System
250k add-ons 17,000 requests/second
150 million views/month 40 million users/month
500+ million api hits/day 450,000 websites
(rewritten from CakePHP) 15 million profiles
75 million comments
(stats from June 2011) (stats from 10/2010)
7. can start small: instrument scheduler
(stats from July 2011. initial launch in jan/feb 2009)
8. Django: Maintenance/Security
Django
- 2011 – 2 updates
- 2010 – 2 updates
- 2009 – 2 updates
- Only update is the core Django code (python files)
- No changes to your code
- No changes to the database
- No changes to HTML templates
- No changes to static or uploaded files
18. Wednesday: The Response
Let‟s make a database!
You can manage it through a website admin!
Sortable column headers!
You can have searching and filters!
19. Wednesday: The Response
Let‟s make a database!
You can manage it through a website admin!
Sortable column headers!
You can have searching and filters!
We can send personalized emails with RSVP links!!
20. Wednesday: The Response
Let‟s make a database!
You can manage it through a website admin!
Sortable column headers!
You can have searching and filters!
We can send personalized emails with RSVP links!!
Just in case, you can download it all back to Excel!
24. Thursday: Response -> Task List (9:30am)
1- Let‟s make a database!
2 - You can manage it through a website admin!
3 - Sortable column headers!
4 - You can have searching and filters!
5 - We can send personalized emails with RSVP links!!
6 - Just in case, you can download it all back to Excel!
25. a bit of setup: choose database (9:15am)
In the settings.py file:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
# Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '/db/mcb_hcom.db3',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
26. a bit of setup: start an “app” (9:20am)
>python manage.py startapp hcom_training
30. data models: 1st think (9:30 to 9:45)
TrainingSession
iname
Trainee training type
first name training datetime
last name room
email (etc, etc)
location
lab_or_office
special
confirmed_training_date
id_md5 LabOffice
(etc., etc.) name
TraineeMessage SpecialDesignation
trainee name
time_sent
to_address
msg
31. data models
class Trainee(models.Model):
""" Trainee Information """
fname = models.CharField(„First Name‟, max_length=50)
lname = models.CharField(„Last Name‟, max_length=50)
email= models.EmailField(blank=True)
confirmed_training_date = models.BooleanField(default=False)
location = models.ForeignKey(LocationInfo) # training session
(+ 13 more fields)
32. data models
class LocationInfo(models.Model):
""" Training Session Information """
name = models.CharField(max_length=255)
training_datetime = models.DateTimeField()
room = models.CharField(max_length=100)
(+2 more fields)
34. Thursday: Response -> Task List (10:02am)
1- Let‟s make a database!
2 - You can manage it through a website admin!
3 - Sortable column headers!
4 - You can have searching and filters!
5 - We can send personalized emails with RSVP links!!
6 - Just in case, you can download it all back to Excel!
35. models.py
>python manage.py sqlall hcom_training
CREATE TABLE `hcom_training_locationinfo` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`name` varchar(255) NOT NULL,
`training_type` varchar(100) NOT NULL,
`training_datetime` datetime NOT NULL,
...
CREATE TABLE `hcom_training_trainee` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`fname` varchar(50) NOT NULL,
`lname` varchar(50) NOT NULL,
`email` varchar(75) NOT NULL,
`confirmed_training_date` bool NOT NULL,
`location_id` integer,
`lab_or_office_id` integer NOT NULL,
...
37. admin.py: 1 line of code (“You can manage it through a website admin!”)
admin.site.register(Trainee)
38. admin.py: 1 line of code (“You can manage it through a website admin!”)
admin.site.register(Trainee)
39. admin.py: 1 line of code (“You can manage it through a website admin!”)
admin.site.register(Trainee)
40. Thursday: Response -> Task List (10:10am)
1- Let‟s make a database!
2 - You can manage it through a website admin!
3 - Sortable column headers!
4 - You can have searching and filters!
5 - We can send personalized emails with RSVP links!!
6 - Just in case, you can download it all back to Excel!
41. admin.py: 3 lines of code (“Sortable column headers!”)
class TraineeAdmin(admin.ModelAdmin):
list_display = ('lname', ’fname', 'email', 'confirmed_training_date’,
'completed_training’)
admin.site.register(Trainee, TraineeAdmin)
42. Thursday: Response -> Task List (10:15am)
1- Let‟s make a database!
2 - You can manage it through a website admin!
3 - Sortable column headers!
4 - You can have searching and filters!
5 - We can send personalized emails with RSVP links!!
6 - Just in case, you can download it all back to Excel!
43. admin.py: 4 lines of code (“You can have searching and filters!)
class TraineeAdmin(admin.ModelAdmin):
list_display = ('lname', ’fname', 'email', 'confirmed_training_date’,
'completed_training’)
search_fields = ('lname', 'fname', 'email', ‘location_room’)
admin.site.register(Trainee, TraineeAdmin)
46. Thursday: Response -> Task List (10:30am)
1- Let‟s make a database!
2 - You can manage it through a website admin!
3 - Sortable column headers!
4 - You can have searching and filters!
5 - We can send personalized emails with RSVP links!!
6 - Just in case, you can download it all back to Excel!
52. models.py -> direct database access
>python manage.py dbshell
SQLite version 3.7.6
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>.tables
hcom_training_laboffice
hcom_training_locationinfo
hcom_training_special
hcom_training_trainee
hcom_training_traineemessage
56. Data In/Out
- Web-based Admin
-Python Shell or Python Scripts/Programs
- dumpdata / loaddata (json, xml, yaml)
- database shell / db specific commands (MySQL, sqlite, etc)
57. All for 2 files!!
1- Let‟s make a database!
2 - You can manage it through a website admin!
3 - Sortable column headers!
4 - You can have searching and filters!
5 - We can send personalized emails with RSVP links!!
6 - Just in case, you can download it all back to Excel!
58. personalized emails: message
Dear Raman Prasad,
You have been selected as an individual who will be placing orders via the Harvard Crimson Online
Marketplace or "HCOM" procurement system on behalf of your lab or group.
For REQUIRED Hands-on Shopper training, please save the SAVE THE DATE:
Time: May 18th, 2011 at 10am
Location: Science Center, Rm. 226.
The training will last 2 hours and lunch will be provided.
To RSVP, please click on the following link:
http://mcb.harvard.edu/hcom/confirm/2812e5cf6d8f21d69c91dddeefb792a7/
If for any reason, you are not able to attend this training, please contact me immediately to make
alternate arrangements.
Thank you.
59. personalized emails: message as a template
Dear {{ trainee.fname }} {{ trainee.lname }},
You have been selected as an individual who will be placing orders via the Harvard Crimson Online
Marketplace or "HCOM" procurement system on behalf of your lab or group.
For REQUIRED Hands-on {{ trainee.training_type }} training, please save the SAVE THE DATE:
Time: {{ trainee.location.training_date|date:"F jS, Y at P" }}
Location: {{ trainee.location.room }}
The training will last 2 hours and lunch will be provided.
To RSVP, please click on the following link:
{% url view_hcom_confirmation trainee.id_md5 %}
If for any reason, you are not able to attend this training, please contact me immediately to make
alternate arrangements.
Thank you.
60. personalized emails: use the template
for trainee in Trainee.objects.all():
msg = render_to_string('confirmation_email.txt’
, { 'trainee': trainee } )
62. personalized emails: the link
http://mcb.harvard.edu/hcom/confirm/2812e5cf6d8f21d69c91dddeefb792a7/
urlpatterns = patterns(
'hcom_training.views'
, url(r'^hcom/confirm/(?P<trainee_id>(w){32})/$',
'view_hcom_confirmation'
, name='view_hcom_confirmation')
)
63. personalized emails: simplified view
def view_hcom_confirmation(request, trainee_id):
"""Simple view showing trainee confirmation page"""
trainee = Trainee.objects.get(id_md5=trainee_id) # get trainee
trainee.confirmed_training_date = True # set confirmed to true
trainee.save() # save the information
# display web page
return render_to_response('hcom_templates/hcom_confirm_page.html'
, { „trainee‟: trainee}
, context_instance=RequestContext(request))
64. personalized emails: the view
def view_hcom_confirmation(request, trainee_id):
"""Simple view showing trainee confirmation page"""
lu = {}
# Find the trainee; make sure he/she exists
try:
trainee = Trainee.objects.get(id_md5=trainee_id)
lu.update({ 'trainee' : trainee })
except Trainee.DoesNotExist:
lu.update({ 'ERR_MSG' : True, 'ERR_trainee_not_found' : True })
return
render_to_response('hcom_templates/hcom_confirm_page.html', lu, context_instance=RequestCont
ext(request))
# Check if the person has already confirmed
if trainee.confirmed_training_date: # Yes, err message
lu.update({ 'ERR_MSG' : True , 'ERR_already_confirmed' : True })
else:
# New confirmation, update database
trainee.confirmed_training_date = True
trainee.save()
# show confirmation page to use
return
render_to_response('hcom_templates/hcom_confirm_page.html', lu, context_instance=RequestCont
ext(request))
65. All for 2 files!!
1- Let‟s make a database!
2 - You can manage it through a website admin!
3 - Sortable column headers!
4 - You can have searching and filters!
5 - We can send personalized emails with RSVP links!!
6 - Just in case, you can download it all back to Excel!
66. export as Excel
used python xlwt library
style_info_cell = easyxf('pattern: pattern solid, fore_colour white; align: wrap on;')
book = xlwt.Workbook(encoding="utf-8") # make Excel workbook
sheet1 = book.add_sheet('hcom training') # add a sheet
row_num = 2
for trainee in Trainee.objects.all():
sheet1.write(row_num, 1, trainee.lname, style_info_cell) # lname
sheet1.write(row_num, 2, trainee.fname, style_info_cell) # fname
sheet1.write(row_num, 3, trainee.email, style_info_cell ) # email
(…)
row_num += 1
Example: https://webapps.sciences.fas.harvard.edu/mcb/mcb-control-panel/hcom_training/
67. All for 2 files!!
1- Let‟s make a database!
2 - You can manage it through a website admin!
3 - Sortable column headers!
4 - You can have searching and filters!
5 - We can send personalized emails with RSVP links!!
6 - Just in case, you can download it all back to Excel!
68. Project Results
- Emails sent out by 3:30/4pm after an hour of Q/A
Time savings
- RSVPs started coming. Database updated as email recipients
clicked link
- 35 people re-scheduled. No need to update shared
spreadsheet. Staff used dropdown box in admin to change
dates and add notes.
- Able to send reminder emails before each training date
69. Project Results
- Filters used to generate attendance spreadsheets
- Tracked “completed training” via the admin
- System used as new employees come on board
- Home on time
- BUT: Should have been a 1.5 to 2 day project
70. Spreadsheets -> Databases
- Genome Modification Center
- 46 tables
- 2,389 objects for 500+ projects
- Life Sciences Course Tracker
- 37 Tables
- 1,293 objects including 798 semesters of course data
73. Learning more .. .
Django official site – Work through the Tutorial!!
https://www.djangoproject.com/
Python
http://python.org
Dive into Python
http://www.diveintopython.net/toc/index.html
Contact
raman_prasad@harvard.edu