Django Tutorial

Django Web Development for Perfectionists with Deadlines Thursday 24 February 2011 » Framework Models » » » A URL

Views 176 Downloads 9 File size 783KB

Report DMCA / Copyright

DOWNLOAD FILE

Recommend stories

Citation preview

Django Web Development for Perfectionists with Deadlines

Thursday 24 February 2011

»

Framework Models

» » »

A URL is mapped to a view. View pulls some objects based on a query. Creates a rendering context.

Templates

» Thursday 24 February 2011

Forget SQL, Django handles the database.

Views

» » » »

Define how a piece of data looks and works.

HTML code with some extra tags that insert some content from the context.

A Django Project » Separated into ‘apps’. » Examples: /news/, /photos/, /events/ » Each app has its own models, views, templates.

» A global URL mapper turns a URL into a view located inside an app.

Thursday 24 February 2011

Speed Through It

Thursday 24 February 2011

Model class Photo(models.Model): name = models.CharField(max_length=100) file = models.ImageField() owner = models.ForeignKey(User) pub_date = models.DateTimeField() description = models.TextField()

Thursday 24 February 2011

URL Map url variable, will be passed as keyword argument to view function

(r‘photos/(?P\d+)/$’, ‘photos.show_photo’), regex describing url path

Thursday 24 February 2011

python package path to view function

View def show_photo(request, id): photo = Photo.objects.get(id=id) context = { ‘photo’: photo } return render_to_response(‘photo.html’, context)

Thursday 24 February 2011

Template {% extends ‘base.html’ %} {% block content %} {{ photo.title }} Uploaded by: {{ photo.owner.username }}


{{ photo.description }}

{% endblock %}

Thursday 24 February 2011

Installing Django » Install Python! (duh) » Install setuptools » $ easy_install django » > C:\Python2x\scripts\easy_install.exe django

Thursday 24 February 2011

Start a Project

» django-admin.py startproject mysite

Thursday 24 February 2011

Start an App » cd mysite » ./manage.py startapp photos

Thursday 24 February 2011

File Layout __init__.py manage.py photos photos/__init__.py photos/models.py photos/tests.py photos/views.py settings.py urls.py templates/base.html templates/photo.html Thursday 24 February 2011

manage.py » ./manage.py startapp [appname] » ./manage.py runserver » ./manage.py syncdb

Thursday 24 February 2011

settings.py » Edit database config. » Set up locale, timezones, translation. » Set template directories. » Load middleware. » Load apps. Thursday 24 February 2011

Built-in Apps » Django comes with loads of built in apps for various purposes.

» User authentication. » Sessions. » Admin site. » Etc etc. Thursday 24 February 2011

Designing URLs page.php script.cgi?pageid=144 StoryPage.aspx

Thursday 24 February 2011

Designing URLs 0,2097,1-1-30-72-407-4752,00.html

Thursday 24 February 2011

Designing URLs photos/ photos/14/ photos/hamilton-at-night/ Thursday 24 February 2011

urls.py from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^admin/', include(admin.site.urls)), (r ^photos/(?P\d+)/$ , photos.show_photo ), (r ^$ , photos.index ), ) Thursday 24 February 2011

About Models »

No SQL needed, Django handles it for whatever kind of database you choose in settings.py.

»

SQLite for dev, deploy on MySQL, move to Postgres later - no problem.

»

Never risk SQL Injection. i.e. concatenating an SQL query with some content a user submitted in a form in order to construct a full query.

»

Django lazily evaluates queries, won’t run a query until you need to enumerate and print the result.

»

Uses QuerySet objects for sorting, filtering, querying.

Thursday 24 February 2011

About QuerySets >>> Photo.objects.all() >>> Photo.objects.filter(uploaded = today()) >>> Photo.objects.filter(name__startswith = ”Pants”) >>> Photo.objects.filter(owner = User.objects.get(username=”theorie”)) Can also union and intersect querysets, drop into SQL whenever you want.

Thursday 24 February 2011

Updating objects >>> p = Photos.objects.get(id=some_id) >>> p.name = “A new name” >>> p.save() # photo has been saved to the db

Thursday 24 February 2011

Admin Site » Rapid development of new features. » Knock out a model in 5 minutes. » Get a writer on the admin site pushing content.

» Finish view logic and templates. » Feature deployed within the hour. Thursday 24 February 2011

Thursday 24 February 2011

Thursday 24 February 2011

Thursday 24 February 2011

Batteries Included » Generic Views » Syndication » Auth/Auth » Comments » i18n/l10n » Caching framework Thursday 24 February 2011

Generic Views from mysite.models import Photo patterns = urlpatterns( , (r ^photos/$ , django.views.generic.list_detail.object_list , { queryset : Photo.objects.all(), paginate_by : 30 } ), Thursday 24 February 2011

Syndication from django.contrib.syndication.feeds import Feed from mysite.models import Photo class PhotoFeed(Feed): title = My Photo Feed link = /photos/ description = Photos from my site def items(self): return Photo.objects.all()[:20] Thursday 24 February 2011

Syndication

» (r’^feeds/photos/$’, PhotoFeed()),

Thursday 24 February 2011

Auth/Auth » »

Abstracted, use any method you want. Built-in Users, Groups, Permissions in django.contrib.auth

» » »

Authenticate using the local database. user = authenticate(username, password) user.login() if user != None

» »

Attach any other auth system you can think of.

»

Write your own, make a class that implements authenticate(user, pass) and get_user(id), add it to AUTHENTICATION_BACKENDS in settings.py

Thursday 24 February 2011

Many available on the internet: LDAP, ActiveDirectory, etc.

Auth/Auth » Netsoc uses our own auth backend, based on the LDAP method.

» Though unless you want to query LDAP

every time you need some user’s info, it’s best to cache the user data in Django’s User database locally as well.

» We also run through the LDAP groups that

the user belongs to and tag the local django copy with things like is_staff and is_superuser if the account is an admin or member of webteam.

Thursday 24 February 2011

Comments {% load comments %} {% get_free_comment_list for photos.photos photo.id as comments %} {% for comment in comments %} {{ comment.person_name }} said:

{{ comment.comment }}

{% endfor %}

Thursday 24 February 2011

Comments

{% free_comment_form for photos.photos photo.id %}

Thursday 24 February 2011

i18n/l10n » Django’s core is translated into 63 languages. » Easy to add localization to your projects. » » » » » »

Thursday 24 February 2011

from django.utils.translation import ugettext as _ _(“This text will be translated”) {% trans “This text will be translated” %} django-admin.py makemessages -l fr django-admin.py compilemessages request.session[‘django_language’] = ‘fr’

Caching » Various caching middleware is included. » Filesystem » Local memory » Memcached » Write your own caching backend. » Add it to CACHES in settings.py » Cache a whole view. » Just cache part of a template, save caches based on tags like username, language code, to keep them relevant.

Thursday 24 February 2011

Learn More » djangoproject.com » Thanks for coming. » Slides are on netsoc.tcd.ie Thursday 24 February 2011