in the hat' >>> "Cat in the {0}".format("hat") 'Cat in the hat' >>> "Cat in the {0} knows nothing about {1}".format("Hat", "That") 'Cat in the Hat knows nothing about That' >>> "Cat in the {thing}".format(thing='hat') 'Cat in the hat' >>> "Cat in the {thing}, where is my {thing}".format(thing='hat') 'Cat in the hat, where is my hat' 23 Tuesday, February 19, 13
10: ... print("a is bigger than 10") ... elif a > 5: ... print("a is bigger than 5") ... else: ... print("a is <= 5") ... a is bigger than 5 Example of a simple if else statement 29 Tuesday, February 19, 13
a / b ... except ZeroDivisionError as exc: ... raise Exception("Wha? Div by zero yo!") ... >>> div(2,0) Traceback (most recent call last): File "<input>", line 1, in <module> File "<input>", line 5, in div Exception: Wha? Div by zero yo! 38 Tuesday, February 19, 13
• https://docs.djangoproject.com/en/ 1.4/intro/tutorial01/ • There isn’t enough time to go over everything, so I skipped some parts. 41 Tuesday, February 19, 13
configured correctly. • Best to do this now before you make any changes. • $ python manage.py runserver • Should have started with no errors. • I’ll come back to runserver a little later 59 Tuesday, February 19, 13
the settings the way they are for now. • Let’s use SQLite for a database • Change DATABASES.default.ENGINE to 'django.db.backends.sqlite3' • Change DATABASES.default.NAME to ‘tutorial.db’ 62 Tuesday, February 19, 13
setting and creates the needed database tables for the apps listed • Creates superuser if one doesn’t exist. • $ python manage.py syncdb 63 Tuesday, February 19, 13
usually named models.py • Contains the essential fields and behaviors of the data you’re storing. • Generally, each model maps to a single database table 66 Tuesday, February 19, 13
that subclasses django.db.models.Model • Each attribute of the model represents a database field. • With all of this, Django gives you an automatically-generated database-access API. • Creates the initial database tables for you. 67 Tuesday, February 19, 13
pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField() Add the following to your polls/models.py 71 Tuesday, February 19, 13
Django to do the following: • Builds the “Create table” sql statement • Creates a python db api for accessing those db tables 72 Tuesday, February 19, 13
about our new app, we need to add our app to our INSTALLED_APPS setting in our Settings.py INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'polls', # <---- We added it here ) 73 Tuesday, February 19, 13
SQL will be run when you kick off syncdb, you can use the “sql” command • $ python manage.py sql polls BEGIN; CREATE TABLE "polls_poll" ( "id" serial NOT NULL PRIMARY KEY, "question" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL ); CREATE TABLE "polls_choice" ( "id" serial NOT NULL PRIMARY KEY, "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id") DEFERRABLE INITIALLY DEFERRED, "choice" varchar(200) NOT NULL, "votes" integer NOT NULL ); COMMIT; 74 Tuesday, February 19, 13
in your models • sqlcustom - Outputs any custom sql statements that are defined for the app • sqlclear - Outputs the necessary drop table statements for the app. • sqlindexes - Outputs the create index statements • sqlall - Outputs all sql (creates, custom, index, etc) for these models 75 Tuesday, February 19, 13
is the shell • $ python manage.py shell • Starts an interactive python shell that lets you play around with your app form the command line. • Install Bpython or Ipython for more features 77 Tuesday, February 19, 13
Import the model classes we just wrote. >>> from polls.models import Poll, Choice >>> Poll.objects.all() [] # No polls are in the system yet. >>> from django.utils import timezone >>> p = Poll(question="What's new?", pub_date=timezone.now()) # Save the object into the database. You have to call save() explicitly. >>> p.save() >>> p.id 1 78 Tuesday, February 19, 13
to make your live easier. import datetime from django.utils import timezone # ... class Poll(models.Model): # ... def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) 81 Tuesday, February 19, 13
the automatic admin interface. • It reads the metadata in your model to provide a powerful, production ready interface • It is disabled by default 82 Tuesday, February 19, 13
import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), ) 85 Tuesday, February 19, 13
your application and it’s models before they will work in the admin • You do this by creating a <app_name>/ admin.py file and configure your models 87 Tuesday, February 19, 13
your models to work in the admin, but we will just use the normal way for now. • Create a polls/admin.py and add the following from polls.models import Poll, Choice from django.contrib import admin admin.site.register(Poll) admin.site.register(Choice) 88 Tuesday, February 19, 13
ways to customize the django admin, we don’t have time today to go into all of them. • Follow the tutorial online to find out more. • https://docs.djangoproject.com/en/ 1.4/intro/tutorial02/ 89 Tuesday, February 19, 13
code lives. It ties your request, model, and template together. • Here is a very simple view from django.http import HttpResponse def index(request): return HttpResponse("Hello, world.") 91 Tuesday, February 19, 13
logic with your urls. You can change the url later on without changing the code. • Uses regular expressions to match urls to views • Allows you to create nice looking urls 93 Tuesday, February 19, 13
some more. • Change the index view to this. from polls.models import Poll from django.http import HttpResponse def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] output = ', '.join([p.question for p in latest_poll_list]) return HttpResponse(output) 96 Tuesday, February 19, 13
and ease. • Clear line between logic and presentation, no code allowed • Has a set of built in tags and filter • Ability to write custom tags and filters • Block based to support template inheritance 97 Tuesday, February 19, 13
is pretty basic, lets add a template to make it better. • create a ‘templates/polls’ directory under polls app. • create a file called index.html 101 Tuesday, February 19, 13
to change our view, to use it. from django.template import Context, loader from polls.models import Poll from django.http import HttpResponse def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] t = loader.get_template('polls/index.html') c = Context({ 'latest_poll_list': latest_poll_list, }) return HttpResponse(t.render(c)) 103 Tuesday, February 19, 13
HTML form data into something useful for views • Also provides validation • 2 types of Django Forms • Model forms • Regular forms 104 Tuesday, February 19, 13
They have fields with attributes, and widgets. • Widgets tell django what type of HTML field to map it too. • Django can create HTML forms for you from a form object. 105 Tuesday, February 19, 13
from django.http import HttpResponseRedirect def contact(request): if request.method == 'POST': # If the form has been submitted... form = ContactForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/thanks/') # Redirect after POST else: form = ContactForm() # An unbound form return render(request, 'contact.html', { 'form': form, }) 107 Tuesday, February 19, 13
but they make it easier to get the form data into models. • Instead of having to move the data from the form to the model, it is done automatically, and saved to the db when save() is called. 109 Tuesday, February 19, 13
can deploy your application for free, and play around with it. • Check out : http://www.dotCloud.com • Django Tutorial: http://docs.dotcloud.com/tutorials/python/django/ 111 Tuesday, February 19, 13
just a quick overview of Django and Python, there is way, way more then this, and I apologize if I skimmed over a part you really wanted to know more about. 113 Tuesday, February 19, 13
have any suggestions on how to make it better, please contact me on twitter (@kencochrane) or send me an email [email protected] 114 Tuesday, February 19, 13