Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to Django Peter Krenesky OSU Open Source Lab slides:

Similar presentations


Presentation on theme: "Intro to Django Peter Krenesky OSU Open Source Lab slides:"— Presentation transcript:

1 Intro to Django Peter Krenesky OSU Open Source Lab slides: http://bit.ly/eiFsvF

2 Projects Projects are a collection of apps (modules) tied together by a settings file. $ django-admin startproject my_new_project

3 Projects $ django-admin startproject tutorial $ ls -og tutorial total 12 -rw-r--r-- 1 0 2011-04-05 13:16 __init__.py -rwxr-xr-x 1 542 2011-04-05 13:16 manage.py -rw-r--r-- 1 3390 2011-04-05 13:16 settings.py -rw-r--r-- 1 486 2011-04-05 13:16 urls.py

4 Settings.py ● Create your database – use sqlite for quick start ● Set INSTALLED_APPS ● Set your paths – DOC_ROOT – the file path of the project – SITE_ROOT – the root url of the project – MEDIA_ROOT – the file path of media – MEDIA_URL – the root url of the project

5 Settings.py: Paths shortcuts for simpler configs DOC_ROOT = os.path.dirname(os.path.realpath(__file__)) MEDIA_ROOT = '%s/media' % DOC_ROOT SITE_ROOT = 'foobar' MEDIA_URL '%s/media' % SITE_URL

6 Manage.py controls your project $./manage.py validate 0 errors $./manage.py syncdb Creating table auth_permission Creating table auth_group_permissions … $./manage.py shell

7 Manage.py creating an app >./manage.py startapp vehicles > ls -og vehicles total 12 -rw-r--r-- 1 0 2011-04-06 09:47 __init__.py -rw-r--r-- 1 57 2011-04-06 09:47 models.py -rw-r--r-- 1 514 2011-04-06 09:47 tests.py -rw-r--r-- 1 26 2011-04-06 09:47 views.py

8 Manage.py running tests >./manage.py test vehicles Creating test database 'default'... Creating table auth_permission Creating table auth_group_permissions ….. ---------------------------------------- Ran 2 tests in 0.003s OK Destroying test database 'default'...

9 Models ● Database is built from the models. ● Models are magic classes, be careful!

10 Models from django.db import models from django.contrib.auth.models import User class Car(models.Model): x = models.IntegerField(default=0) y = models.IntegerField(default=0) user = models.ForeignKey(user, null=True)

11 Models >>> from tutorial.vehicles.models import * >>> car = Car() >>> print car.x, car.y 0, 0 >>> car.x = 10 >>> car.y = 20 >>> car.save()

12 QuerySets lazily executed queries >>> q = Car.objects.all() >>> print q [,, ] >>> print type(q) >>> q.filter(x=10) [ ]

13 QuerySets filtering methods accept kwargs >>> filter = Car.objects.filter >>> q = filter(x=10, y=42) >>> q = filter(x__gt=10) >>> q = filter(user__username='peter') >>> q = filter(user__id__lt=10)

14 QuerySets more filtering ● exclude(**kw) – excludes matching records ● get(**kw) – fetch a single record ● update(**kw) – update records ● delete(**kw) – delete records

15 QuerySets more filtering ● exclude(**kw) – excludes matching records ● get(**kw) – fetch a single record ● update(**kw) – update records ● delete(**kw) – delete records

16 QuerySets have many methods ● count() - counts records, use instead of len() ● exists() - quicker than count() ● order_by() - order fields

17 QuerySets make them efficient ● values() - return dict instead of full objects ● values_list() - return just the data you need ● defer() - defer loading of fields ● only() - defer loading of fields ● select_related() - select related models

18 QuerySets Q clauses for complex queries from django.db.models import Q # accepts kwargs just like other methods clause = Q(x=10) clause = Q(x=10, user__id__gt=10) # clauses can be combined with OR/AND clause = Q(x=10) | Q(x=20) & Q(y=9) clause |= Q(y=42) # use the clause with filter, exclude, etc. Car.objects.filter(clause) Car.objects.filter(clause, x=10)

19 QuerySets aggregate methods from django.db.models import Sum, Count, Avg # aggregate runs across the full result set Car.objects.aggregate(count=Count('x')) # you can filter your queries first Car.objects.filter(x=10).aggregate(c=Count('x')) # annotation adds a value to each class Car.objects.annotate(avg=Avg('x')) # values() causes grouping Car.objects.annotate(avg=Avg('x')).values('y')

20 Views methods that respond to requests from django.http import HttpResponse def hello(request): “”” basic view “”” return HttpResponse(“Hello”)

21 urls.py where you map urls to views url( # regex matching /car/123 r”^car/(?P \d+)$”, # path to view “vehicles.views.car_detail”, # optional kwargs {}, # reverse name lookup name='cars-list' )

22 urls.py reverse lookups >>> from django.core.urlresolvers import reverse >>> print reverse('car-detail', args=[123]) '/car/123'

23 Views Views can easily send json for ajax import simplejson from django.http import HttpResponse def send_json(request): x = [1, 2, 3] json = simplejson.dumps(x) return HttpResponse(json mimetype='application/json' )

24 Views a basic view that lists objects from django.shortcuts import render def list_cars(request): “”” list_cars “”” cars = Car.objects.all() return render(“list.html”, {'cars':cars} )

25 Templates TEMPLATE + CONTEXT = Rendered Content {% for car in cars %} {{car.x}}, {{car.y}} {% endfor %}

26 Templates inheritance and blocks for extensible layouts {% block head %} {% endblock %} {% block content %} {% endblock %}

27 Templates inheritance and blocks for extensible layouts {% extends base.html %} {% block content %} This goes in the body tag! {% endblock %}

28 Templates reuse snippets with includes {% block content %} {% include 'list.html' %} {% endblock %}

29 Forms make processing data easy from django import forms class MyForm(forms.Form): awesome = forms.BooleanField()

30 Forms make processing data easy >>> data = {'awesome':True} >>> form = MyForm(data) >>> print form.is_valid() True def process(request): form = MyForm(request.POST)

31 Forms make processing data easy def process(request): # prevent x-site attacks with post if request.method != 'POST': return HttpResponseNotAllowed() # create and validate form form = MyForm(request.POST) if form.is_valid(): url = reverse('success') return HttpResponseRedirect(url) # return form errors errors = json.dumps(form.errors) return HttpResponse(errors)

32 Forms rendering html for forms {% block content %} {{ form }} {{ form.as_table }} {{ form.as_p }} {{ form.errors }} {% endblock %}

33 Project Layout advanced layout for larger projects project_root – app ● views_folder – object_or_feature.py ● templates – app_name ● object_or_feature ● list.html ● detail.html ● table.html

34 Questions? Slides: http://bit.ly/eiFsvF Peter Krenesky Email: peter@osuosl.orgpeter@osuosl.org twitter: @kreneskyp CODE SPRINT AFTER THE SESSIONS!


Download ppt "Intro to Django Peter Krenesky OSU Open Source Lab slides:"

Similar presentations


Ads by Google