Version 1 (modified by paolo <paolo@…>, 18 years ago) ( diff )

Django at a glance, Italian translation.

..
  ==================
  Django at a glance
  ==================

======================
Primo sguardo a Django
======================

.. sidebar:: Primo sguardo a Django
  :subtitle: traduzione in lingua italiana.

  Documento originale: `Django at a glance`_
  
  Traduzione: paolo `<paolo@php3.it>`
  
  Aggiornato alla revisione: 2871

.. _Django at a glance: http://www.djangoproject.com/documentation/overview/

..
  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.

Poiché Django è stato sviluppato in un dipartimento di pubblicazione
giornalistica in cui le informazioni da pubblicare sono molte e frequenti,  
si è cercato di semplificare le operazioni legate allo sviluppo Web rendendole
veloci e snelle. Questo documento è un'introduzione informale alla stesura di
applicazioni Web basate su database realizzate con 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
  reference. Please see our more-detailed Django documentation_ when you're ready
  to start a project.
  
  .. _documentation: http://www.djangoproject.com/documentation/

L'obiettivo di questo documento è fornire un numero sufficiente di notizie
tecniche per rendere comprensibili i principi di funzionamento di Django, 
senza però voler essere né un tutorial né un reference. Quando sarai pronto
per cominciare un progetto affidati alla documentazione_ che descrive Django
con maggior dettaglio. 

.. _documentazione: http://www.djangoproject.com/documentation/

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

Progetta il modello
===================

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

Sebbene sia possibile usare Django senza un database, viene fornito un mapper
oggetti-relazionale che consente di descrivere la struttura dei dati
dell'applicazione con codice Python.

..
  The data-model syntax offers many rich ways of representing your models -- so
  far, it's been solving two years' worth of database-schema problems. Here's a
  quick example::
  
      class Reporter(models.Model):
          full_name = models.CharField(maxlength=70)
  
          def __str__(self):
              return self.full_name
  
      class Article(models.Model):
          pub_date = models.DateTimeField()
          headline = models.CharField(maxlength=200)
          article = models.TextField()
          reporter = models.ForeignKey(Reporter)
  
          def __str__(self):
              return self.headline

La sintassi per la modellazione dei dati offre una ricca gamma di possibilità --
oramai sono due anni che viene usata con successo per risolvere problematiche
legate alla generazione di schemi di database. Questo è un breve esempio:: 

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

        def __str__(self):
            return self.full_name

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

        def __str__(self):
            return self.headline

..
  Install it
  ==========

Installa il modello
===================

..
  Next, run the Django command-line utility to create the database tables
  automatically::
  
      manage.py syncdb
  
  The ``syncdb`` command looks at all your available models and creates tables
  in your database for whichever tables don't already exist.

In seguito, quando invocherai l'utility apposita offerta da Django, le tabelle
saranno create automaticamente::

    manage.py syncdb

Il comando ``syncdb`` considera tutti i modelli disponibili e crea le tabelle
all'interno del database, per tutte le tabelle non pre-esistenti.

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

Usa le API a corredo
====================

..
  With that, you've got a free, and rich, Python API to access your data. The API
  is created on the fly: No code generation necessary::
  
      >>> 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()
      [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)
      John Smith
      >>> Reporter.objects.get(full_name__startswith='John')
      John Smith
      >>> Reporter.objects.get(full_name__contains='mith')
      John Smith
      >>> Reporter.objects.get(id=2)
      Traceback (most recent call last):
          ...
      DoesNotExist: Reporter does not exist for {'id__exact': 2}
  
      # Create an article.
      >>> from datetime import datetime
      >>> a = Article(pub_date=datetime.now(), headline='Django is cool',
      ...     article='Yeah.', reporter=r)
      >>> a.save()
  
      # Now the article is in the database.
      >>> Article.objects.all()
      [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()
      [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")
      [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()

Grazie alle operazioni che hai appena compiuto, ti viene messo a disposizione
un completo insieme di API Python, creato in modo automatico, per consentirti 
di accedere ai dati della tua applicazione: non è necessaria alcuna generazione
di codice::

    >>> from mysite.models import Reporter, Article

    # Non sono ancora stati inseriti reporter.
    >>> Reporter.objects.all()
    []

    # Crea un nuovo Reporter.
    >>> r = Reporter(full_name='John Smith')

    # Salva l'oggetto nel database. save() deve esplicitamente essere invocato.
    >>> r.save()

    # Ora l'oggetto ha un ID.
    >>> r.id
    1

    # Ora il nuovo reporter è nel database.
    >>> Reporter.objects.all()
    [John Smith]

    # I campi sono rappresentati come attributi dell'oggetto Python.
    >>> r.full_name
    'John Smith'

    # Django offre un insieme di API per effettuare interrogazioni sui dati.
    >>> Reporter.objects.get(id=1)
    John Smith
    >>> Reporter.objects.get(full_name__startswith='John')
    John Smith
    >>> Reporter.objects.get(full_name__contains='mith')
    John Smith
    >>> Reporter.objects.get(id=2)
    Traceback (most recent call last):
        ...
    DoesNotExist: Reporter does not exist for {'id__exact': 2}

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

    # Ora l'articolo è nel database.
    >>> Article.objects.all()
    [Django is cool]

    # Gli oggetti Article incorporano le API per l'accesso agli oggetti Reporter a cui sono associati.
    >>> r = a.reporter
    >>> r.full_name
    'John Smith'

    # >Si verifica anche il vice versa: gli oggetti Reporter incorporano le API per l'accesso agli oggetti Article.
    >>> r.article_set.all()
    [Django is cool]

    # Le API seguono le relazioni secondo le tue esigenze, generando 
    # operazioni di JOIN efficienti al posto tuo, in modo trasparente. 
    # Il seguente codice trova tutti gli articoli di un reporter il cui nome comincia con "John".
    >>> Article.objects.filter(reporter__full_name__startswith="John")
    [Django is cool]

    # Modifica un oggetto alterandone gli attributi e invocando save().
    >>> r.full_name = 'Billy Goat'
    >>> r.save()

    # Elimina un oggetto tramite delete().
    >>> r.delete()

..
  A dynamic admin interface: It's not just scaffolding -- it's the whole house
  ============================================================================

Un'interfaccia di amministrazione dinamica: non solo un'impalcatura, ma l'intera casa
======================================================================================

..
  Once your models are defined, Django can automatically create a professional,
  production ready administrative interface -- a Web site that lets authenticated
  users add, change and delete objects. It's as easy as adding a line of code to
  your model classes::

      class Article(models.Model):
          pub_date = models.DateTimeField()
          headline = models.CharField(maxlength=200)
          article = models.TextField()
          reporter = models.ForeignKey(Reporter)
          class Admin: pass

Una volta definiti i modelli, Django può creare automaticamente un'interfaccia
amministrativa professionale e pronta per essere usata in produzione -- si tratta di
un sito Web che consente agli utenti autenticati di aggiungere, modificare ed
eliminare oggetti. Poterla avere è semplice come aggiungere una linea di codice
alle classi dei modelli per cui si desidera un'interfaccia di amministrazione::

    class Article(models.Model): pub_date = models.DateTimeField()
        headline = models.CharField(maxlength=200)
        article = models.TextField()
        reporter = models.ForeignKey(Reporter)
        class Admin: pass

..
  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.

L'idea di base è che le modifiche al sito vengano effettuate da un gruppo di 
persone, o da un cliente, o magari semplicemente da te -- senza però l'onere di
dover creare l'interfaccia di gestione se lo scopo è semplicemente quello di 
gestire contenuti.

..
  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.

Un tipico ciclo di vita nella creazione di applicazioni con Django consiste
nella realizzazione dei modelli e nel disporre di un sito di amministrazione
funzionante nel più breve tempo possibile, in modo che lo staff o i clienti
possano cominciare l'inserimento dei dati. Solo in seguito si darà importanza
alla parte di presentazione dei dati al pubblico.

..
  Design your URLs
  ================

Progetta gli URL
================

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

Presentare URL puliti ed eleganti è un dettaglio importante in una
applicazione Web di elevata qualità. Django favorisce la progettazione di
splendidi URL in cui non compaiono informazioni superflue come ``.php`` o
``.asp``.

..
  To design URLs for an app, you create a Python module called a URLconf. 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.

La progettazione degli URL di un'applicazione avviene creando un modulo Python
chiamato URLconf. Lo si può pensare come la tabella dei contenuti
dell'applicazione e contiene semplici corrispondenze tra maschere di URL (URL
patterns) e funzioni Python. Un'altra finalità dei moduli URLconf è tenere
separata la gestione degli URL dal codice Python dell'applicazione.

..
  Here's what a URLconf might look like for the above ``Reporter``/``Article``
  example above::
  
      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'),
      )

Ecco come potrebbe apparire un URLconf per l'esempio ``Reporter``/``Article``
esposto in precedenza:: 

    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'),
    )


..
  The code above maps URLs, as simple regular expressions, to the location of
  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.

Questo codice associa gli URL, espressi come semplici espressioni regolari, a
funzioni di callback scritte in Python (chiamate "view"). La "cattura" dei
valori specificati assieme agli URL avviene usando parentesi nelle espressioni
regolari. Quando un utente richiede una pagina, Django scorre ogni espressione
regolare, rispettando l'ordine di presentazione, interrompendo la ricerca non
appena viene trovato un URL in grado di soddisfare l'espressione regolare (se non
vengono trovate corrispondenze si fa ricorso ad una view speciale di tipo 404). 
Le espressioni regolari sono compilate in fase di caricamento, perciò il procedimento
di invocazione di una funzione in base all'URL richiesto risulta incredibilmente
prestazionale.

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

Quando una delle espressioni regolari corrisponde, Django importa e invoca la view
associata, che semplicemente è una funzione Python. Ad ogni view viene
passato un oggetto request -- contenente i metadati relativi alla richiesta -- 
e i valori catturati nell'espressione regolare.

..
  For example, if a user requested the URL "/articles/2005/05/39323/", Django
  would call the function ``mysite.views.article_detail(request,
  '2005', '05', '39323')``.

Ad esempio, se un utente dovesse richiede l'URL "/articles/2005/05/39323/", Django
invocherebbe la funzione ``mysite.views.article_detail(request, '2005', '05', '39323')``.

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

Scrivi le view
==============

..
  Each view is responsible for doing one of two things: Returning an
  ``HttpResponse`` object containing the content for the requested page, or
  raising an exception such as ``Http404``. The rest is up to you.

Ogni view ha la responsabilità di restituire un oggetto ``HttpResponse``
contenente la pagina di risposta oppure sollevare un'eccezione come ``Http404``.
Il resto dei compiti spetta a te.

..
  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
  ``year_archive`` from above::
  
      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})

Generalmente, una view ottiene i dati definiti dai parametri, carica un
template (un modello della pagina che verrà restituita in seguito ad una
richiesta) e popola il template con i dati ottenuti. La view ``year_archive``
potrebbe verosimilmente essere qualcosa di questo tipo::

    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})

..
  This example uses Django's template system, which has several powerful
  features but strives to stay simple enough for non-programmers to use.

Il codice dell'esempio usa il meccanismo di gestione dei template offerto da 
Django, che pur esponendo funzionalità avanzate risulta sufficientemente
semplice per poter essere usato anche da chi non è un programmatori.

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

Progetta i template
===================

.. The code above loads the ``news/year_archive.html`` template.

Nell'esempio, la vista ``year_archive`` carica il template
``news/year_archive.html``.

.. 
  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
  for templates. If a template doesn't exist in the first directory, it checks the
  second, and so on.

Django minimizza le ridondanze tra i modelli di pagina implementando un percorso di
ricerca dei template. Nelle impostazioni di configurazione puoi specificare una lista 
di directory dedicate ad ospitare i template. Se si cerca un template non presente
nella prima directory, viene cercato nella seguente, e così via.

..
  Let's say the ``news/article_detail.html`` template was found. Here's what that
  might look like::
  
      {% 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 %}

Ipotizziamo che il template ``news/article_detail.html`` venga trovato.
Potrebbe verosimilmente apparire così::

    {% extends "base.html" %}

    {% block title %}Articoli del {{ year }}{% endblock %}

    {% block content %}
    <h1>Articoli del {{ year }}</h1>

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

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

Le variabili sono circondate da coppie di parentesi graffe. ``{{article.headline }}``
significa "Restituisci il valore dell'attributo headline
di article". Le parentesi graffe non vengono utilizzate esclusivamente per il lookup
degli attributi, ma anche per ottenere i valori corrispondenti a chiavi di
dizionario, per il lookup basato su indici o per richiamare funzioni.

..
  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
  the given format (as found in PHP's date function; yes, there is one good idea
  in PHP).

Nota come le "pipe" (il carattere "|") in stile Unix vengono utilizzate in 
``{{ article.pub_date|date:"F j, Y" }}``. Questo particolare costrutto è un filtro 
di template, e viene usato per filtrare il contenuto di una variabile. In
questo caso, il filtro ``date`` formatta un oggetto ``datetime`` di Python nel
formato specificato (come descritto nella funzione ``date`` di PHP; ebbene sì,
c'è una buona idea in PHP).

..
  You can chain together as many filters as you'd like. You can write custom
  filters. You can write custom template tags, which run custom Python code behind
  the scenes.

Puoi concatenare un numero arbitrario di filtri, puoi scrivere filtri
personalizzati e, se hai la necessità di eseguire codice Python nel template in
modo trasparente, puoi anche personalizzare i tag di template. 

..
  Finally, Django uses the concept of "template inheritance": That's what the
  ``{% 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
  in templates: Each template has to define only what's unique to that template.

Per finire, Django adotta il concetto di "ereditarietà dei tempate": è ciò che
avviene in ``{% extends "base.html" %}``. Significa "Prima carica il
template con nome 'base', dove sono definiti blocchi vuoti, poi riempi
questi blocchi con altri blocchi". In sostanza, la ridondanza nei template viene
drasticamente ridotta: ogni template deve definire solamente gli elementi che 
lo caratterizzano rendendolo unico.

..
  Here's what the "base.html" template might look like::
  
Il template "base.html" potrebbe essere::

    <html>
    <head>
        <title>{% block title %}{% endblock %}</title>
    </head>
    <body>
        <img src="sitelogo.gif" alt="Logo" />
        {% 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
  easy as changing a single file -- the base template.

Evitando spiegazioni prolisse, questo template definisce l'aspetto 
comune del sito (il look-and-feel) con il logo, emette a disposizione aree vuote che 
saranno riempite da template figli. Il restyling di un sito si riduce al ritocco di 
un singolo file -- il template base.

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

L'ereditarietà dei template consente anche di creare differenti versioni di un
sito usando template di base diversi che condividono gli stessi template
figli. Gli autori di Django hanno usato questa tecnica per creare edizioni di
siti adatte alla visualizzazione su telefoni cellulari, semplicemente creando
un nuovo template di base.

..
  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
  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.

Sappi che non sei obbligato ad usare il sistema di template di Django, se ne 
preferisci altri. Nonostante esso sia particolarmente ben integrato nel framework, 
nulla ti forza ad usarlo. Per lo stesso motivo non ti è nemmeno imposto l'obbligo
di usare le API di Django per l'interfacciamento ai database. Puoi usare un altro
sistema di astrazione per database, puoi leggere file XML, file su disco o fare 
qualsiasi altra cosa sia nelle tue intenzioni. Ogni frammento di Django -- i modelli, 
le view, i template -- è indipendente dal seguente. 

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

Questo è solo un assaggio
=========================

..
  This has been only a quick overview of Django's functionality. Some more useful
  features:
  
      * A caching framework that integrates with memcached or other backends.
      * A syndication framework that makes creating RSS and Atom feeds as easy as
        writing a small Python class.
      * More sexy automatically-generated admin features -- this overview barely
        scratched the surface.

Il contenuto di questo documento è soltanto una rapida panoramica di quelle che
sono le funzionalità di Django. Alcune altre caratteristiche, ancora più utili,
sono:

    * Un sistema di caching che si integra con svariati backend, tra cui
      memcached.
    * Un sistema di syndication che rende la creazione di feed RSS e Atom
      un'operazione tanto semplice da essere paragonabile alla scrittura
      di una piccola classe Python.
    * Funzionalità di amministrazione generate automaticamente -- in questa
      introduzione non si è andati oltre la superficie.

..
  The next obvious steps are for you to `download Django`_, read `the tutorial`_
  and join `the community`_. Thanks for your interest!
  
  .. _download Django: http://www.djangoproject.com/download/
  .. _the tutorial: http://www.djangoproject.com/documentation/tutorial1/
  .. _the community: http://www.djangoproject.com/community/

Ora per te, i prossimi passi logici saranno `scaricare Django`_, leggere 
`il tutorial`_ e diventare parte della `comunità`_. 
Grazie per l'interesse mostrato!

.. _scaricare Django: http://www.djangoproject.com/download/
.. _il tutorial: http://www.djangoproject.com/documentation/tutorial1/
.. _comunità: http://www.djangoproject.com/community/

Note: See TracWiki for help on using the wiki.
Back to Top