overview.txt 12.3 KB
Newer Older
1 2 3
==================
Django at a glance
==================
4 5 6 7 8 9 10

Because Django was developed in a fast-paced newsroom environment, it was
designed to make common Web-development tasks fast and easy. Here's an informal
overview of how to write a database-driven Web app with Django.

The goal of this document is to give you enough technical specifics to
understand how Django works, but this isn't intended to be a tutorial or
11
reference -- but we've got both! When you're ready to start a project, you can
12 13
:doc:`start with the tutorial </intro/tutorial01>` or :doc:`dive right into more
detailed documentation </topics/index>`.
14 15 16 17

Design your model
=================

18
Although you can use Django without a database, it comes with an
19
`object-relational mapper`_ in which you describe your database layout in Python
20
code.
21

22 23
.. _object-relational mapper: http://en.wikipedia.org/wiki/Object-relational_mapping

24
The :doc:`data-model syntax </topics/db/models>` offers many rich ways of
25
representing your models -- so far, it's been solving many years' worth of
26 27
database-schema problems. Here's a quick example, which might be saved in
the file ``mysite/news/models.py``::
28

29
    from django.db import models
30

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

34
        def __str__(self):              # __unicode__ on Python 2
35
            return self.full_name
36

37
    class Article(models.Model):
38
        pub_date = models.DateField()
39
        headline = models.CharField(max_length=200)
40
        content = models.TextField()
41
        reporter = models.ForeignKey(Reporter)
42

43
        def __str__(self):              # __unicode__ on Python 2
44 45 46 47 48
            return self.headline

Install it
==========

49
Next, run the Django command-line utility to create the database tables
50 51 52
automatically:

.. code-block:: bash
53

54
    $ python manage.py migrate
55

56 57 58
The :djadmin:`migrate` command looks at all your available models and creates
tables in your database for whichever tables don't already exist, as well as
optionally providing :doc:`much richer schema control </topics/migrations>`.
59 60 61 62

Enjoy the free API
==================

63 64 65
With that, you've got a free, and rich, :doc:`Python API </topics/db/queries>`
to access your data. The API is created on the fly, no code generation
necessary:
66 67

.. code-block:: python
68

69 70
    # Import the models we created from our "news" app
    >>> from news.models import Reporter, Article
71

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

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

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

82 83 84
    # Now it has an ID.
    >>> r.id
    1
85

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

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

94 95
    # Django provides a rich database lookup API.
    >>> Reporter.objects.get(id=1)
96
    <Reporter: John Smith>
97
    >>> Reporter.objects.get(full_name__startswith='John')
98
    <Reporter: John Smith>
99
    >>> Reporter.objects.get(full_name__contains='mith')
100
    <Reporter: John Smith>
101
    >>> Reporter.objects.get(id=2)
102 103
    Traceback (most recent call last):
        ...
104
    DoesNotExist: Reporter matching query does not exist.
105

106
    # Create an article.
107 108
    >>> from datetime import date
    >>> a = Article(pub_date=date.today(), headline='Django is cool',
109
    ...     content='Yeah.', reporter=r)
110
    >>> a.save()
111

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

116
    # Article objects get API access to related Reporter objects.
117
    >>> r = a.reporter
118 119
    >>> r.full_name
    'John Smith'
120

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

125 126 127
    # 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".
128
    >>> Article.objects.filter(reporter__full_name__startswith='John')
129
    [<Article: Django is cool>]
130

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

135 136 137
    # Delete an object with delete().
    >>> r.delete()

138
A dynamic admin interface: it's not just scaffolding -- it's the whole house
139 140
============================================================================

141
Once your models are defined, Django can automatically create a professional,
142 143 144
production ready :doc:`administrative interface </ref/contrib/admin/index>` --
a Web site that lets authenticated users add, change and delete objects. It's
as easy as registering your model in the admin site::
145 146 147 148

    # In models.py...

    from django.db import models
149

150
    class Article(models.Model):
151
        pub_date = models.DateField()
152
        headline = models.CharField(max_length=200)
153
        content = models.TextField()
154
        reporter = models.ForeignKey(Reporter)
155

156 157

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

159 160 161 162
    import models
    from django.contrib import admin

    admin.site.register(models.Article)
163 164 165 166 167

The philosophy here is that your site is edited by a staff, or a client, or
maybe just you -- and you don't want to have to deal with creating backend
interfaces just to manage content.

168 169 170
One typical workflow in creating Django apps is to create models and get the
admin sites up and running as fast as possible, so your staff (or clients) can
start populating data. Then, develop the way data is presented to the public.
171 172

Design your URLs
173
================
174 175

A clean, elegant URL scheme is an important detail in a high-quality Web
176 177
application. Django encourages beautiful URL design and doesn't put any cruft
in URLs, like ``.php`` or ``.asp``.
178

179
To design URLs for an app, you create a Python module called a :doc:`URLconf
180 181 182
</topics/http/urls>`. A table of contents for your app, it contains a simple
mapping between URL patterns and Python callback functions. URLconfs also serve
to decouple URLs from Python code.
183

184
Here's what a URLconf might look like for the ``Reporter``/``Article``
185
example above::
186

187
    from django.conf.urls import url
188

189
    urlpatterns = [
190 191 192
        url(r'^articles/([0-9]{4})/$', 'news.views.year_archive'),
        url(r'^articles/([0-9]{4})/([0-9]{2})/$', 'news.views.month_archive'),
        url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', 'news.views.article_detail'),
193
    ]
194

195
The code above maps URLs, as simple `regular expressions`_, to the location of
196 197 198 199 200 201
Python callback functions ("views"). The regular expressions use parenthesis to
"capture" values from the URLs. When a user requests a page, Django runs
through each pattern, in order, and stops at the first one that matches the
requested URL. (If none of them matches, Django calls a special-case 404 view.)
This is blazingly fast, because the regular expressions are compiled at load
time.
202

203 204
.. _regular expressions: http://docs.python.org/2/howto/regex.html

205
Once one of the regexes matches, Django imports and calls the given view, which
206
is a simple Python function. Each view gets passed a request object --
207
which contains request metadata -- and the values captured in the regex.
208 209

For example, if a user requested the URL "/articles/2005/05/39323/", Django
210
would call the function ``news.views.article_detail(request,
211
'2005', '05', '39323')``.
212 213 214 215 216

Write your views
================

Each view is responsible for doing one of two things: Returning an
217 218 219
:class:`~django.http.HttpResponse` object containing the content for the
requested page, or raising an exception such as :class:`~django.http.Http404`.
The rest is up to you.
220 221 222

Generally, a view retrieves data according to the parameters, loads a template
and renders the template with the retrieved data. Here's an example view for
223
``year_archive`` from above::
224

225
    from django.shortcuts import render
226

227 228
    def year_archive(request, year):
        a_list = Article.objects.filter(pub_date__year=year)
229 230
        context = {'year': year, 'article_list': a_list}
        return render(request, 'news/year_archive.html', context)
231

232
This example uses Django's :doc:`template system </topics/templates>`, which has
233 234
several powerful features but strives to stay simple enough for non-programmers
to use.
235 236 237 238

Design your templates
=====================

239
The code above loads the ``news/year_archive.html`` template.
240 241 242

Django has a template search path, which allows you to minimize redundancy among
templates. In your Django settings, you specify a list of directories to check
243 244
for templates with :setting:`TEMPLATE_DIRS`. If a template doesn't exist in the
first directory, it checks the second, and so on.
245

246
Let's say the ``news/year_archive.html`` template was found. Here's what that
247 248 249
might look like:

.. code-block:: html+django
250

251
    {% extends "base.html" %}
252

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

255
    {% block content %}
256 257 258
    <h1>Articles for {{ year }}</h1>

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

265 266
Variables are surrounded by double-curly braces. ``{{ article.headline }}``
means "Output the value of the article's headline attribute." But dots aren't
267
used only for attribute lookup. They also can do dictionary-key lookup, index
268
lookup and function calls.
269 270 271 272

Note ``{{ article.pub_date|date:"F j, Y" }}`` uses a Unix-style "pipe" (the "|"
character). This is called a template filter, and it's a way to filter the value
of a variable. In this case, the date filter formats a Python datetime object in
Ben Longden's avatar
Ben Longden committed
273
the given format (as found in PHP's date function).
274

275 276 277 278
You can chain together as many filters as you'd like. You can write :ref:`custom
template filters <howto-writing-custom-template-filters>`. You can write
:doc:`custom template tags </howto/custom-template-tags>`, which run custom
Python code behind the scenes.
279

280
Finally, Django uses the concept of "template inheritance". That's what the
281 282 283
``{% extends "base.html" %}`` does. It means "First load the template called
'base', which has defined a bunch of blocks, and fill the blocks with the
following blocks." In short, that lets you dramatically cut down on redundancy
284
in templates: each template has to define only what's unique to that template.
285

286
Here's what the "base.html" template, including the use of :doc:`static files
287
</howto/static-files/index>`, might look like:
288 289

.. code-block:: html+django
290

291
    {% load staticfiles %}
292 293
    <html>
    <head>
294
        <title>{% block title %}{% endblock %}</title>
295 296
    </head>
    <body>
297
        <img src="{% static "images/sitelogo.png" %}" alt="Logo" />
298 299 300 301 302 303
        {% block content %}{% endblock %}
    </body>
    </html>

Simplistically, it defines the look-and-feel of the site (with the site's logo),
and provides "holes" for child templates to fill. This makes a site redesign as
304
easy as changing a single file -- the base template.
305

306 307
It also lets you create multiple versions of a site, with different base
templates, while reusing child templates. Django's creators have used this
308 309
technique to create strikingly different mobile versions of sites -- simply by
creating a new base template.
310

311 312 313
Note that you don't have to use Django's template system if you prefer another
system. While Django's template system is particularly well-integrated with
Django's model layer, nothing forces you to use it. For that matter, you don't
314 315 316 317
have to use Django's database API, either. You can use another database
abstraction layer, you can read XML files, you can read files off disk, or
anything you want. Each piece of Django -- models, views, templates -- is
decoupled from the next.
318 319 320 321 322 323 324

This is just the surface
========================

This has been only a quick overview of Django's functionality. Some more useful
features:

325 326
* A :doc:`caching framework </topics/cache>` that integrates with memcached
  or other backends.
327

328 329
* A :doc:`syndication framework </ref/contrib/syndication>` that makes
  creating RSS and Atom feeds as easy as writing a small Python class.
330

331 332
* More sexy automatically-generated admin features -- this overview barely
  scratched the surface.
333

334 335
The next obvious steps are for you to `download Django`_, read :doc:`the
tutorial </intro/tutorial01>` and join `the community`_. Thanks for your
336
interest!
337

338 339
.. _download Django: https://www.djangoproject.com/download/
.. _the community: https://www.djangoproject.com/community/