Django at a glance

Original: http://docs.djangoproject.com/en/dev/intro/overview/

Design your model

Django kann auch ohne Datenbank benutzt werden, das objektrelational Mapping ist jedoch eines seiner Stärken.

Beispiel:

class Reporter(models.Model):
    full_name = models.CharField(max_length=70)

    def __unicode__(self):
        return self.full_name

class Article(models.Model):
    pub_date = models.DateTimeField()
    headline = models.CharField(max_length=200)
    content = models.TextField()
    reporter = models.ForeignKey(Reporter)

    def __unicode__(self):
        return self.headline

Install it

Tabellen erstellen:

manage.py syncdb

Enjoy the free API

Die API ist direkt verfügbar (ohne fehleranfällige Codegenerierung):

>>> from mysite.models import Reporter, Article

# No reporters are in the system yet.
>>> Reporter.objects.all()
[]

# Create a new Reporter.
>>> r = Reporter(full_name='John Smith')

# Save the object into the database. You have to call save() explicitly.
>>> r.save()

# Now it has an ID.
>>> r.id
1

# Now the new reporter is in the database.
>>> Reporter.objects.all()
[<Reporter: John Smith>]

# Fields are represented as attributes on the Python object.
>>> r.full_name
'John Smith'

# Django provides a rich database lookup API.
>>> Reporter.objects.get(id=1)
<Reporter: John Smith>
>>> Reporter.objects.get(full_name__startswith='John')
<Reporter: John Smith>
>>> Reporter.objects.get(full_name__contains='mith')
<Reporter: John Smith>
>>> Reporter.objects.get(id=2)
Traceback (most recent call last):
    ...
DoesNotExist: Reporter matching query does not exist.

# Create an article.
>>> from datetime import datetime
>>> a = Article(pub_date=datetime.now(), headline='Django is cool',
...     content='Yeah.', reporter=r)
>>> a.save()

# Now the article is in the database.
>>> Article.objects.all()
[<Article: Django is cool>]

# Article objects get API access to related Reporter objects.
>>> r = a.reporter
>>> r.full_name
'John Smith'

# And vice versa: Reporter objects get API access to Article objects.
>>> r.article_set.all()
[<Article: Django is cool>]

# The API follows relationships as far as you need, performing efficient
# JOINs for you behind the scenes.
# This finds all articles by a reporter whose name starts with "John".
>>> Article.objects.filter(reporter__full_name__startswith="John")
[<Article: Django is cool>]

# Change an object by altering its attributes and calling save().
>>> r.full_name = 'Billy Goat'
>>> r.save()

# Delete an object with delete().
>>> r.delete()

A dynamic admin interface: it’s not just scaffolding – it’s the whole house

Das contrib-Modul “admin” ermöglicht es die Tabellen zu bearbeiten (INSERT, UPDATE, DELETE):

# In admin.py in the same directory...

import models
from django.contrib import admin

admin.site.register(models.Article)

Design your URLs

Schöne URLs: ohne .php oder .asp auch nicht /cgi-bin/edit?article=123.

Beispiel urls.py:

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^articles/(\d{4})/$', 'mysite.views.year_archive'),
    (r'^articles/(\d{4})/(\d{2})/$', 'mysite.views.month_archive'),
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'mysite.views.article_detail'),
)

URL “/articles/2005/05/39323/” –> Artikel aus Mai 2005 mit ID 39323 bearbeiten URL “/articles/2005/” –> Zeige die Artikel des Jahres 2005.

Write your views

Ein View gibt ein django.http.HttpResponse Objekt zurück.

Das Template year_archive.html wird verwendet:

def year_archive(request, year):
    a_list = Article.objects.filter(pub_date__year=year)
    return render_to_response('news/year_archive.html', {'year': year, 'article_list': a_list})

Design your templates

{% extends "base.html" %}

{% block title %}Articles for {{ year }}{% endblock %}

{% block content %}
<h1>Articles for {{ year }}</h1>

{% for article in article_list %}
<p>{{ article.headline }}</p>
<p>By {{ article.reporter.full_name }}</p>
<p>Published {{ article.pub_date|date:"F j, Y" }}</p>
{% endfor %}
{% endblock %}

Templatesprache unterstützt Vererbung: Nur gewisse Blöcke des Eltern-Templates werden ersetzt, der Rest wird übernommen.

Hinweis: Ich verwende die Templatesprache kaum.

This is just the surface

und es gibt noch viel mehr...