Django

Code

Changeset 2787

Show
Ignore:
Timestamp:
04/28/06 21:53:35 (2 years ago)
Author:
adrian
Message:

magic-removal: Proofread docs/overview.txt

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/magic-removal/docs/overview.txt

    r2721 r2787  
    1717================= 
    1818 
    19 Start by describing your database layout in Python code. Django's data-model API 
    20 offers many rich ways of representing your models -- so far, it's been 
    21 solving two years' worth of database-schema problems. Here's a quick example:: 
    22  
    23     class Reporter(meta.Model): 
    24         full_name = meta.CharField(maxlength=70) 
    25  
    26         def __repr__(self): 
     19Although you can use Django without a database, it comes with an 
     20object-relational mapper in which you describe your database layout in Python 
     21code. 
     22 
     23The data-model syntax offers many rich ways of representing your models -- so 
     24far, it's been solving two years' worth of database-schema problems. Here's a 
     25quick example:: 
     26 
     27    class Reporter(models.Model): 
     28        full_name = models.CharField(maxlength=70) 
     29 
     30        def __str__(self): 
    2731            return self.full_name 
    2832 
    29     class Article(meta.Model): 
    30         pub_date = meta.DateTimeField() 
    31         headline = meta.CharField(maxlength=200) 
    32         article = meta.TextField() 
    33         reporter = meta.ForeignKey(Reporter) 
    34  
    35         def __repr__(self): 
     33    class Article(models.Model): 
     34        pub_date = models.DateTimeField() 
     35        headline = models.CharField(maxlength=200) 
     36        article = models.TextField() 
     37        reporter = models.ForeignKey(Reporter) 
     38 
     39        def __str__(self): 
    3640            return self.headline 
    3741 
     
    3943========== 
    4044 
    41 Next, run the Django command-line utility. It'll create the database tables for 
    42 you automatically, in the database specified in your Django settings. Django 
    43 works best with PostgreSQL, although we've recently added beta MySQL 
    44 support and other database adapters are on the way:: 
    45  
    46     django-admin.py install news 
     45Next, run the Django command-line utility to create the database tables 
     46automatically:: 
     47 
     48    manage.py syncdb 
     49 
     50The ``syncdb`` command looks at all your available models and creates tables 
     51in your database for whichever tables don't already exist. 
    4752 
    4853Enjoy the free API 
     
    5257is created on the fly: No code generation necessary:: 
    5358 
    54     # Modules are dynamically created within django.models. 
    55     # Their names are plural versions of the model class names. 
    56     >>> from django.models.news import reporters, articles 
     59    >>> from mysite.models import Reporter, Article 
    5760 
    5861    # No reporters are in the system yet. 
    59     >>> reporters.get_list() 
     62    >>> Reporter.objects.all() 
    6063    [] 
    6164 
    6265    # Create a new Reporter. 
    63     >>> r = reporters.Reporter(full_name='John Smith') 
     66    >>> r = Reporter(full_name='John Smith') 
    6467 
    6568    # Save the object into the database. You have to call save() explicitly. 
     
    7174 
    7275    # Now the new reporter is in the database. 
    73     >>> reporters.get_list() 
     76    >>> Reporter.objects.all() 
    7477    [John Smith] 
    7578 
     
    7881    'John Smith' 
    7982 
    80     # Django provides a rich database lookup API that's entirely driven by keyword arguments
    81     >>> reporters.get_object(id__exact=1) 
     83    # Django provides a rich database lookup API
     84    >>> Reporter.objects.get(id=1) 
    8285    John Smith 
    83     >>> reporters.get_object(full_name__startswith='John') 
     86    >>> Reporter.objects.get(full_name__startswith='John') 
    8487    John Smith 
    85     >>> reporters.get_object(full_name__contains='mith') 
     88    >>> Reporter.objects.get(full_name__contains='mith') 
    8689    John Smith 
    87     >>> reporters.get_object(id__exact=2) 
     90    >>> Reporter.objects.get(id=2) 
    8891    Traceback (most recent call last): 
    8992        ... 
    90     django.models.news.ReporterDoesNotExist: Reporter does not exist for {'id__exact': 2} 
    91  
    92     # Lookup by a primary key is the most common case, so Django provides a 
    93     # shortcut for primary-key exact lookups. 
    94     # The following is identical to reporters.get_object(id__exact=1). 
    95     >>> reporters.get_object(pk=1) 
    96     John Smith 
     93    DoesNotExist: Reporter does not exist for {'id__exact': 2} 
    9794 
    9895    # Create an article. 
    9996    >>> from datetime import datetime 
    100     >>> a = articles.Article(pub_date=datetime.now(), headline='Django is cool', article='Yeah.', reporter_id=1) 
     97    >>> a = Article(pub_date=datetime.now(), headline='Django is cool', 
     98    ...     article='Yeah.', reporter=r) 
    10199    >>> a.save() 
    102100 
    103101    # Now the article is in the database. 
    104     >>> articles.get_list() 
     102    >>> Article.objects.all() 
    105103    [Django is cool] 
    106104 
    107105    # Article objects get API access to related Reporter objects. 
    108     >>> r = a.get_reporter() 
     106    >>> r = a.reporter 
    109107    >>> r.full_name 
    110108    'John Smith' 
    111109 
    112110    # And vice versa: Reporter objects get API access to Article objects. 
    113     >>> r.get_article_list() 
     111    >>> r.article_set.all() 
    114112    [Django is cool] 
    115113 
    116     # The API follows relationships as far as you need. 
    117     # Find all articles by a reporter whose name starts with "John". 
    118     >>> articles.get_list(reporter__full_name__startswith="John") 
     114    # The API follows relationships as far as you need, performing efficient 
     115    # JOINs for you behind the scenes. 
     116    # This finds all articles by a reporter whose name starts with "John". 
     117    >>> Article.objects.filter(reporter__full_name__startswith="John") 
    119118    [Django is cool] 
    120119 
     
    129128============================================================================ 
    130129 
    131 Once your models are defined, Django can automatically create an administrative 
    132 interface -- a Web site that lets authenticated users add, change and 
    133 delete objects. It's as easy as adding an extra ``admin`` attribute to your 
    134 model classes:: 
    135  
    136     class Article(meta.Model): 
    137         pub_date = meta.DateTimeField() 
    138         headline = meta.CharField(maxlength=200) 
    139         article = meta.TextField() 
    140         reporter = meta.ForeignKey(Reporter) 
    141         class Meta: 
    142             admin = meta.Admin() 
     130Once your models are defined, Django can automatically create a professional, 
     131production ready administrative interface -- a Web site that lets authenticated 
     132users add, change and delete objects. It's as easy as adding a line of code to 
     133your model classes:: 
     134 
     135    class Article(models.Model): 
     136        pub_date = models.DateTimeField() 
     137        headline = models.CharField(maxlength=200) 
     138        article = models.TextField() 
     139        reporter = models.ForeignKey(Reporter) 
     140        class Admin: pass 
    143141 
    144142The philosophy here is that your site is edited by a staff, or a client, or 
     
    146144interfaces just to manage content. 
    147145 
    148 Our typical workflow at World Online is to create models and get the admin sites 
    149 up and running as fast as possible, so our staff journalists can start 
    150 populating data. Then we develop the way data is presented to the public. 
     146One typical workflow in creating Django apps is to create models and get the 
     147admin sites up and running as fast as possible, so your staff (or clients) can 
     148start populating data. Then, develop the way data is presented to the public. 
    151149 
    152150Design your URLs 
     
    154152 
    155153A clean, elegant URL scheme is an important detail in a high-quality Web 
    156 application. Django lets you design URLs however you want, with no framework 
    157 limitations. 
    158  
    159 To design URLs for an app, you create a Python module. For the above 
    160 Reporter/Article example, here's what that might look like:: 
     154application. Django encourages beautiful URL design and doesn't put any cruft 
     155in URLs, like ``.php`` or ``.asp``. 
     156 
     157To design URLs for an app, you create a Python module called a URLconf. A table 
     158of contents for your app, it contains a simple mapping between URL patterns and 
     159Python callback functions. URLconfs also serve to decouple URLs from Python 
     160code. 
     161 
     162Here's what a URLconf might look like for the above ``Reporter``/``Article`` 
     163example above:: 
    161164 
    162165    from django.conf.urls.defaults import * 
    163166 
    164167    urlpatterns = patterns('', 
    165         (r'^/articles/(?P<year>\d{4})/$', 'myproject.news.views.year_archive'), 
    166         (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'myproject.news.views.month_archive'), 
    167         (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<article_id>\d+)/$', 'myproject.news.views.article_detail'), 
     168        (r'^/articles/(\d{4})/$', 'mysite.views.year_archive'), 
     169        (r'^/articles/(\d{4})/(\d{2})/$', 'mysite.views.month_archive'), 
     170        (r'^/articles/(\d{4})/(\d{2})/(\d+)/$', 'mysite.views.article_detail'), 
    168171    ) 
    169172 
    170 The code above maps URLs, as regular expressions, to the location of Python 
    171 callback functions (views). The regular expressions use parenthesis to "capture" 
    172 values from the URLs. When a user requests a page, Django runs through each 
    173 regular expression, in order, and stops at the first one that matches the 
    174 requested URL. (If none of them matches, Django calls a special 404 view.) This 
    175 is blazingly fast, because the regular expressions are compiled at load time. 
     173The code above maps URLs, as simple regular expressions, to the location of 
     174Python callback functions ("views"). The regular expressions use parenthesis to 
     175"capture" values from the URLs. When a user requests a page, Django runs 
     176through each pattern, in order, and stops at the first one that matches the 
     177requested URL. (If none of them matches, Django calls a special-case 404 view.) 
     178This is blazingly fast, because the regular expressions are compiled at load 
     179time. 
    176180 
    177181Once one of the regexes matches, Django imports and calls the given view, which 
    178182is a simple Python function. Each view gets passed a request object -- 
    179 which contains request metadata and lets you access GET and POST data as simple 
    180 dictionaries -- and the values captured in the regex, via keyword 
    181 arguments. 
     183which contains request metadata -- and the values captured in the regex. 
    182184 
    183185For example, if a user requested the URL "/articles/2005/05/39323/", Django 
    184186would call the function ``myproject.news.views.article_detail(request, 
    185 year='2005', month='05', article_id='39323')``. 
     187'2005', '05', '39323')``. 
    186188 
    187189Write your views 
     
    194196Generally, a view retrieves data according to the parameters, loads a template 
    195197and renders the template with the retrieved data. Here's an example view for 
    196 article_detail from above:: 
    197  
    198     def article_detail(request, year, month, article_id): 
    199         # Use the Django API to find an object matching the URL criteria. 
    200         a = get_object_or_404(articles, pub_date__year=year, pub_date__month=month, pk=article_id
    201         return render_to_response('news/article_detail.html', {'article': a}) 
    202  
    203 This example uses Django's template system, which has several key features
     198``year_archive`` from above:: 
     199 
     200    def year_archive(request, year): 
     201        a_list = Article.objects.filter(pub_date__year=year) 
     202        return render_to_response('news/year_archive.html', {'article_list': a_list}
     203 
     204This example uses Django's template system, which has several powerful 
     205features but strives to stay simple enough for non-programmers to use
    204206 
    205207Design your templates 
    206208===================== 
    207209 
    208 The code above loads the ``news/article_detail`` template. 
     210The code above loads the ``news/year_archive.html`` template. 
    209211 
    210212Django has a template search path, which allows you to minimize redundancy among 
     
    213215second, and so on. 
    214216 
    215 Let's say the ``news/article_detail`` template was found. Here's what that migh
    216 look like:: 
    217  
    218     {% extends "base" %} 
     217Let's say the ``news/article_detail.html`` template was found. Here's what tha
     218might look like:: 
     219 
     220    {% extends "base.html" %} 
    219221 
    220222    {% block title %}{{ article.headline }}{% endblock %} 
     
    227229    {% endblock %} 
    228230 
    229  
    230 It should look straightforward. Variables are surrounded by double-curly braces. 
    231 ``{{ article.headline }}`` means "Output the value of the article's headline 
    232 attribute." But dots aren't used only for attribute lookup: They also can do 
    233 dictionary-key lookup, index lookup and function calls (as is the case with 
    234 ``article.get_reporter``). 
     231Variables are surrounded by double-curly braces. ``{{ article.headline }}`` 
     232means "Output the value of the article's headline attribute." But dots aren't 
     233used only for attribute lookup: They also can do dictionary-key lookup, index 
     234lookup and function calls (as is the case with ``article.get_reporter``). 
    235235 
    236236Note ``{{ article.pub_date|date:"F j, Y" }}`` uses a Unix-style "pipe" (the "|" 
     
    244244the scenes. 
    245245 
    246 Finally, Django uses the concept of template inheritance: That's what the ``{% 
    247 extends "base" %}`` does. It means "First load the template called 'base', which 
    248 has defined a bunch of blocks, and fill the blocks with the following blocks." 
    249 In short, that lets you dramatically cut down on redundancy in templates: Each 
    250 template has to define only what's unique to that template. 
    251  
    252 Here's what the "base" template might look like:: 
     246Finally, Django uses the concept of "template inheritance": That's what the 
     247``{% extends "base.html" %}`` does. It means "First load the template called 
     248'base', which has defined a bunch of blocks, and fill the blocks with the 
     249following blocks." In short, that lets you dramatically cut down on redundancy 
     250in templates: Each template has to define only what's unique to that template. 
     251 
     252Here's what the "base.html" template might look like:: 
    253253 
    254254    <html> 
     
    266266easy as changing a single file -- the base template. 
    267267 
     268It also lets you create multiple versions of a site, with different base 
     269templates, while reusing child templates. Django's creators have used this 
     270technique to create strikingly different cell-phone editions of sites -- simply 
     271by creating a new base template. 
     272 
    268273Note that you don't have to use Django's template system if you prefer another 
    269274system. While Django's template system is particularly well-integrated with 
    270275Django's model layer, nothing forces you to use it. For that matter, you don't 
    271 have to use Django's API, either. You can use another database abstraction 
    272 layer, you can read XML files, you can read files off disk, or anything you 
    273 want. Each piece of Django -- models, views, templates -- is decoupled 
    274 from the next. 
     276have to use Django's database API, either. You can use another database 
     277abstraction layer, you can read XML files, you can read files off disk, or 
     278anything you want. Each piece of Django -- models, views, templates -- is 
     279decoupled from the next. 
    275280 
    276281This is just the surface