Web Programming in Python With Django
Web Programming in Python With Django
with Django!
Instructors:
Steve Levine '11
Maria Rodriguez '11
Geoffrey Thomas '10
[email protected]
http://sipb.mit.edu/iap/django/
Wednesday, January 27th
django [jāngō]
-noun
1. a shiny web framework that allows one to
build dynamic, professional-looking websites
in python: Need to make a slick website?
Use django!
2. masculine form of popular Hasbro game
Jenga® (will not be discussed tonight)
3. magic
Funk-tacular Features
projects or “apps” are pluggable
object-relational mapper: combines the advantages
of having a database with the advantages of using
an object-oriented programming language
database allows for efficient data storage and
retrieval
Python allows for cleaner and more readable code
Funk-tacular Features
automatic admin interface offers the functionality
of adding, editing, and deleting items within a
database in a graphical, user-friendly way
flexible template language that provides a way to
retrieve data and display it on a webpage in its
desired format
url design is elegant and easy to read
Marvelous Websites Made the
Django Way:
Models & Views
App Layer
User Interface
(HTTP Output)
Controller View
MVC
Model
Database Layer
MySQL: Database
Marvelous Websites Made the
Django Way:
Models & Views
App Layer: Outputs HTML (controls how data is displayed to the user)
MVC Layer
2. View: The View controls the access and filtration of data in order to be
passed onto the app layer for display.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
Magnificent Models
Can easily create instances of your model:
p = Poll(question="What's up?",
pub_date=datetime.datetime.now())
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
return render_to_response('polls/index.html', {'poll_list': poll_list})
Templates
Templates, Tags, & Tricks
URLs URLConf
Django was written in a newsroom environment, with a very clear separation between
“content publishers” and the “public” site. Site managers use the system to add
news stories, events, sports scores, etc., and that content is displayed on the public
site. Django solves the problem of creating a unified interface for site
administrators to edit content.
The admin isn’t necessarily intended to be used by site visitors; it’s for site managers.”
Reference: http://docs.djangoproject.com/en/dev/intro/tutorial02/
http://docs.djangoproject.com/en/dev/intro/tutorial02/
Forms
Fun with Forms
Why use them?
1. Automatically generate form widgets.
2. Input validation.
3. Redisplay a form after invalid input.
4. Convert submitted form data to Python data types.
Fun with Forms
Example:
<h1>{{ poll.question }}</h1>