| | 1 | {{{ |
| | 2 | #!rst |
| | 3 | |
| | 4 | .. |
| | 5 | ================== |
| | 6 | Django at a glance |
| | 7 | ================== |
| | 8 | |
| | 9 | ====================== |
| | 10 | Primo sguardo a Django |
| | 11 | ====================== |
| | 12 | |
| | 13 | .. sidebar:: Primo sguardo a Django |
| | 14 | :subtitle: traduzione in lingua italiana. |
| | 15 | |
| | 16 | Documento originale: `Django at a glance`_ |
| | 17 | |
| | 18 | Traduzione: paolo `<paolo@php3.it>` |
| | 19 | |
| | 20 | Aggiornato alla revisione: 2871 |
| | 21 | |
| | 22 | .. _Django at a glance: http://www.djangoproject.com/documentation/overview/ |
| | 23 | |
| | 24 | .. |
| | 25 | Because Django was developed in a fast-paced newsroom environment, it was |
| | 26 | designed to make common Web-development tasks fast and easy. Here's an informal |
| | 27 | overview of how to write a database-driven Web app with Django. |
| | 28 | |
| | 29 | Poiché Django è stato sviluppato in un dipartimento di pubblicazione |
| | 30 | giornalistica in cui le informazioni da pubblicare sono molte e frequenti, |
| | 31 | si è cercato di semplificare le operazioni legate allo sviluppo Web rendendole |
| | 32 | veloci e snelle. Questo documento è un'introduzione informale alla stesura di |
| | 33 | applicazioni Web basate su database realizzate con Django. |
| | 34 | |
| | 35 | .. |
| | 36 | The goal of this document is to give you enough technical specifics to |
| | 37 | understand how Django works, but this isn't intended to be a tutorial or |
| | 38 | reference. Please see our more-detailed Django documentation_ when you're ready |
| | 39 | to start a project. |
| | 40 | |
| | 41 | .. _documentation: http://www.djangoproject.com/documentation/ |
| | 42 | |
| | 43 | L'obiettivo di questo documento è fornire un numero sufficiente di notizie |
| | 44 | tecniche per rendere comprensibili i principi di funzionamento di Django, |
| | 45 | senza però voler essere né un tutorial né un reference. Quando sarai pronto |
| | 46 | per cominciare un progetto affidati alla documentazione_ che descrive Django |
| | 47 | con maggior dettaglio. |
| | 48 | |
| | 49 | .. _documentazione: http://www.djangoproject.com/documentation/ |
| | 50 | |
| | 51 | .. |
| | 52 | Design your model |
| | 53 | ================= |
| | 54 | |
| | 55 | Progetta il modello |
| | 56 | =================== |
| | 57 | |
| | 58 | .. |
| | 59 | Although you can use Django without a database, it comes with an |
| | 60 | object-relational mapper in which you describe your database layout in Python |
| | 61 | code. |
| | 62 | |
| | 63 | Sebbene sia possibile usare Django senza un database, viene fornito un mapper |
| | 64 | oggetti-relazionale che consente di descrivere la struttura dei dati |
| | 65 | dell'applicazione con codice Python. |
| | 66 | |
| | 67 | .. |
| | 68 | The data-model syntax offers many rich ways of representing your models -- so |
| | 69 | far, it's been solving two years' worth of database-schema problems. Here's a |
| | 70 | quick example:: |
| | 71 | |
| | 72 | class Reporter(models.Model): |
| | 73 | full_name = models.CharField(maxlength=70) |
| | 74 | |
| | 75 | def __str__(self): |
| | 76 | return self.full_name |
| | 77 | |
| | 78 | class Article(models.Model): |
| | 79 | pub_date = models.DateTimeField() |
| | 80 | headline = models.CharField(maxlength=200) |
| | 81 | article = models.TextField() |
| | 82 | reporter = models.ForeignKey(Reporter) |
| | 83 | |
| | 84 | def __str__(self): |
| | 85 | return self.headline |
| | 86 | |
| | 87 | La sintassi per la modellazione dei dati offre una ricca gamma di possibilità -- |
| | 88 | oramai sono due anni che viene usata con successo per risolvere problematiche |
| | 89 | legate alla generazione di schemi di database. Questo è un breve esempio:: |
| | 90 | |
| | 91 | class Reporter(models.Model): |
| | 92 | full_name = models.CharField(maxlength=70) |
| | 93 | |
| | 94 | def __str__(self): |
| | 95 | return self.full_name |
| | 96 | |
| | 97 | class Article(models.Model): |
| | 98 | pub_date = models.DateTimeField() |
| | 99 | headline = models.CharField(maxlength=200) |
| | 100 | article = models.TextField() |
| | 101 | reporter = models.ForeignKey(Reporter) |
| | 102 | |
| | 103 | def __str__(self): |
| | 104 | return self.headline |
| | 105 | |
| | 106 | .. |
| | 107 | Install it |
| | 108 | ========== |
| | 109 | |
| | 110 | Installa il modello |
| | 111 | =================== |
| | 112 | |
| | 113 | .. |
| | 114 | Next, run the Django command-line utility to create the database tables |
| | 115 | automatically:: |
| | 116 | |
| | 117 | manage.py syncdb |
| | 118 | |
| | 119 | The ``syncdb`` command looks at all your available models and creates tables |
| | 120 | in your database for whichever tables don't already exist. |
| | 121 | |
| | 122 | In seguito, quando invocherai l'utility apposita offerta da Django, le tabelle |
| | 123 | saranno create automaticamente:: |
| | 124 | |
| | 125 | manage.py syncdb |
| | 126 | |
| | 127 | Il comando ``syncdb`` considera tutti i modelli disponibili e crea le tabelle |
| | 128 | all'interno del database, per tutte le tabelle non pre-esistenti. |
| | 129 | |
| | 130 | .. |
| | 131 | Enjoy the free API |
| | 132 | ================== |
| | 133 | |
| | 134 | Usa le API a corredo |
| | 135 | ==================== |
| | 136 | |
| | 137 | .. |
| | 138 | With that, you've got a free, and rich, Python API to access your data. The API |
| | 139 | is created on the fly: No code generation necessary:: |
| | 140 | |
| | 141 | >>> from mysite.models import Reporter, Article |
| | 142 | |
| | 143 | # No reporters are in the system yet. |
| | 144 | >>> Reporter.objects.all() |
| | 145 | [] |
| | 146 | |
| | 147 | # Create a new Reporter. |
| | 148 | >>> r = Reporter(full_name='John Smith') |
| | 149 | |
| | 150 | # Save the object into the database. You have to call save() explicitly. |
| | 151 | >>> r.save() |
| | 152 | |
| | 153 | # Now it has an ID. |
| | 154 | >>> r.id |
| | 155 | 1 |
| | 156 | |
| | 157 | # Now the new reporter is in the database. |
| | 158 | >>> Reporter.objects.all() |
| | 159 | [John Smith] |
| | 160 | |
| | 161 | # Fields are represented as attributes on the Python object. |
| | 162 | >>> r.full_name |
| | 163 | 'John Smith' |
| | 164 | |
| | 165 | # Django provides a rich database lookup API. |
| | 166 | >>> Reporter.objects.get(id=1) |
| | 167 | John Smith |
| | 168 | >>> Reporter.objects.get(full_name__startswith='John') |
| | 169 | John Smith |
| | 170 | >>> Reporter.objects.get(full_name__contains='mith') |
| | 171 | John Smith |
| | 172 | >>> Reporter.objects.get(id=2) |
| | 173 | Traceback (most recent call last): |
| | 174 | ... |
| | 175 | DoesNotExist: Reporter does not exist for {'id__exact': 2} |
| | 176 | |
| | 177 | # Create an article. |
| | 178 | >>> from datetime import datetime |
| | 179 | >>> a = Article(pub_date=datetime.now(), headline='Django is cool', |
| | 180 | ... article='Yeah.', reporter=r) |
| | 181 | >>> a.save() |
| | 182 | |
| | 183 | # Now the article is in the database. |
| | 184 | >>> Article.objects.all() |
| | 185 | [Django is cool] |
| | 186 | |
| | 187 | # Article objects get API access to related Reporter objects. |
| | 188 | >>> r = a.reporter |
| | 189 | >>> r.full_name |
| | 190 | 'John Smith' |
| | 191 | |
| | 192 | # And vice versa: Reporter objects get API access to Article objects. |
| | 193 | >>> r.article_set.all() |
| | 194 | [Django is cool] |
| | 195 | |
| | 196 | # The API follows relationships as far as you need, performing efficient |
| | 197 | # JOINs for you behind the scenes. |
| | 198 | # This finds all articles by a reporter whose name starts with "John". |
| | 199 | >>> Article.objects.filter(reporter__full_name__startswith="John") |
| | 200 | [Django is cool] |
| | 201 | |
| | 202 | # Change an object by altering its attributes and calling save(). |
| | 203 | >>> r.full_name = 'Billy Goat' |
| | 204 | >>> r.save() |
| | 205 | |
| | 206 | # Delete an object with delete(). |
| | 207 | >>> r.delete() |
| | 208 | |
| | 209 | Grazie alle operazioni che hai appena compiuto, ti viene messo a disposizione |
| | 210 | un completo insieme di API Python, creato in modo automatico, per consentirti |
| | 211 | di accedere ai dati della tua applicazione: non è necessaria alcuna generazione |
| | 212 | di codice:: |
| | 213 | |
| | 214 | >>> from mysite.models import Reporter, Article |
| | 215 | |
| | 216 | # Non sono ancora stati inseriti reporter. |
| | 217 | >>> Reporter.objects.all() |
| | 218 | [] |
| | 219 | |
| | 220 | # Crea un nuovo Reporter. |
| | 221 | >>> r = Reporter(full_name='John Smith') |
| | 222 | |
| | 223 | # Salva l'oggetto nel database. save() deve esplicitamente essere invocato. |
| | 224 | >>> r.save() |
| | 225 | |
| | 226 | # Ora l'oggetto ha un ID. |
| | 227 | >>> r.id |
| | 228 | 1 |
| | 229 | |
| | 230 | # Ora il nuovo reporter è nel database. |
| | 231 | >>> Reporter.objects.all() |
| | 232 | [John Smith] |
| | 233 | |
| | 234 | # I campi sono rappresentati come attributi dell'oggetto Python. |
| | 235 | >>> r.full_name |
| | 236 | 'John Smith' |
| | 237 | |
| | 238 | # Django offre un insieme di API per effettuare interrogazioni sui dati. |
| | 239 | >>> Reporter.objects.get(id=1) |
| | 240 | John Smith |
| | 241 | >>> Reporter.objects.get(full_name__startswith='John') |
| | 242 | John Smith |
| | 243 | >>> Reporter.objects.get(full_name__contains='mith') |
| | 244 | John Smith |
| | 245 | >>> Reporter.objects.get(id=2) |
| | 246 | Traceback (most recent call last): |
| | 247 | ... |
| | 248 | DoesNotExist: Reporter does not exist for {'id__exact': 2} |
| | 249 | |
| | 250 | # Crea un articolo. |
| | 251 | >>> from datetime import datetime |
| | 252 | >>> a = Article(pub_date=datetime.now(), headline='Django is cool', |
| | 253 | ... article='Yeah.', reporter=r) |
| | 254 | >>> a.save() |
| | 255 | |
| | 256 | # Ora l'articolo è nel database. |
| | 257 | >>> Article.objects.all() |
| | 258 | [Django is cool] |
| | 259 | |
| | 260 | # Gli oggetti Article incorporano le API per l'accesso agli oggetti Reporter a cui sono associati. |
| | 261 | >>> r = a.reporter |
| | 262 | >>> r.full_name |
| | 263 | 'John Smith' |
| | 264 | |
| | 265 | # >Si verifica anche il vice versa: gli oggetti Reporter incorporano le API per l'accesso agli oggetti Article. |
| | 266 | >>> r.article_set.all() |
| | 267 | [Django is cool] |
| | 268 | |
| | 269 | # Le API seguono le relazioni secondo le tue esigenze, generando |
| | 270 | # operazioni di JOIN efficienti al posto tuo, in modo trasparente. |
| | 271 | # Il seguente codice trova tutti gli articoli di un reporter il cui nome comincia con "John". |
| | 272 | >>> Article.objects.filter(reporter__full_name__startswith="John") |
| | 273 | [Django is cool] |
| | 274 | |
| | 275 | # Modifica un oggetto alterandone gli attributi e invocando save(). |
| | 276 | >>> r.full_name = 'Billy Goat' |
| | 277 | >>> r.save() |
| | 278 | |
| | 279 | # Elimina un oggetto tramite delete(). |
| | 280 | >>> r.delete() |
| | 281 | |
| | 282 | .. |
| | 283 | A dynamic admin interface: It's not just scaffolding -- it's the whole house |
| | 284 | ============================================================================ |
| | 285 | |
| | 286 | Un'interfaccia di amministrazione dinamica: non solo un'impalcatura, ma l'intera casa |
| | 287 | ====================================================================================== |
| | 288 | |
| | 289 | .. |
| | 290 | Once your models are defined, Django can automatically create a professional, |
| | 291 | production ready administrative interface -- a Web site that lets authenticated |
| | 292 | users add, change and delete objects. It's as easy as adding a line of code to |
| | 293 | your model classes:: |
| | 294 | |
| | 295 | class Article(models.Model): |
| | 296 | pub_date = models.DateTimeField() |
| | 297 | headline = models.CharField(maxlength=200) |
| | 298 | article = models.TextField() |
| | 299 | reporter = models.ForeignKey(Reporter) |
| | 300 | class Admin: pass |
| | 301 | |
| | 302 | Una volta definiti i modelli, Django può creare automaticamente un'interfaccia |
| | 303 | amministrativa professionale e pronta per essere usata in produzione -- si tratta di |
| | 304 | un sito Web che consente agli utenti autenticati di aggiungere, modificare ed |
| | 305 | eliminare oggetti. Poterla avere è semplice come aggiungere una linea di codice |
| | 306 | alle classi dei modelli per cui si desidera un'interfaccia di amministrazione:: |
| | 307 | |
| | 308 | class Article(models.Model): pub_date = models.DateTimeField() |
| | 309 | headline = models.CharField(maxlength=200) |
| | 310 | article = models.TextField() |
| | 311 | reporter = models.ForeignKey(Reporter) |
| | 312 | class Admin: pass |
| | 313 | |
| | 314 | .. |
| | 315 | The philosophy here is that your site is edited by a staff, or a client, or |
| | 316 | maybe just you -- and you don't want to have to deal with creating backend |
| | 317 | interfaces just to manage content. |
| | 318 | |
| | 319 | L'idea di base è che le modifiche al sito vengano effettuate da un gruppo di |
| | 320 | persone, o da un cliente, o magari semplicemente da te -- senza però l'onere di |
| | 321 | dover creare l'interfaccia di gestione se lo scopo è semplicemente quello di |
| | 322 | gestire contenuti. |
| | 323 | |
| | 324 | .. |
| | 325 | One typical workflow in creating Django apps is to create models and get the |
| | 326 | admin sites up and running as fast as possible, so your staff (or clients) can |
| | 327 | start populating data. Then, develop the way data is presented to the public. |
| | 328 | |
| | 329 | Un tipico ciclo di vita nella creazione di applicazioni con Django consiste |
| | 330 | nella realizzazione dei modelli e nel disporre di un sito di amministrazione |
| | 331 | funzionante nel più breve tempo possibile, in modo che lo staff o i clienti |
| | 332 | possano cominciare l'inserimento dei dati. Solo in seguito si darà importanza |
| | 333 | alla parte di presentazione dei dati al pubblico. |
| | 334 | |
| | 335 | .. |
| | 336 | Design your URLs |
| | 337 | ================ |
| | 338 | |
| | 339 | Progetta gli URL |
| | 340 | ================ |
| | 341 | |
| | 342 | .. |
| | 343 | A clean, elegant URL scheme is an important detail in a high-quality Web |
| | 344 | application. Django encourages beautiful URL design and doesn't put any cruft |
| | 345 | in URLs, like ``.php`` or ``.asp``. |
| | 346 | |
| | 347 | Presentare URL puliti ed eleganti è un dettaglio importante in una |
| | 348 | applicazione Web di elevata qualità. Django favorisce la progettazione di |
| | 349 | splendidi URL in cui non compaiono informazioni superflue come ``.php`` o |
| | 350 | ``.asp``. |
| | 351 | |
| | 352 | .. |
| | 353 | To design URLs for an app, you create a Python module called a URLconf. A table |
| | 354 | of contents for your app, it contains a simple mapping between URL patterns and |
| | 355 | Python callback functions. URLconfs also serve to decouple URLs from Python |
| | 356 | code. |
| | 357 | |
| | 358 | La progettazione degli URL di un'applicazione avviene creando un modulo Python |
| | 359 | chiamato URLconf. Lo si può pensare come la tabella dei contenuti |
| | 360 | dell'applicazione e contiene semplici corrispondenze tra maschere di URL (URL |
| | 361 | patterns) e funzioni Python. Un'altra finalità dei moduli URLconf è tenere |
| | 362 | separata la gestione degli URL dal codice Python dell'applicazione. |
| | 363 | |
| | 364 | .. |
| | 365 | Here's what a URLconf might look like for the above ``Reporter``/``Article`` |
| | 366 | example above:: |
| | 367 | |
| | 368 | from django.conf.urls.defaults import * |
| | 369 | |
| | 370 | urlpatterns = patterns('', |
| | 371 | (r'^/articles/(\d{4})/$', 'mysite.views.year_archive'), |
| | 372 | (r'^/articles/(\d{4})/(\d{2})/$', 'mysite.views.month_archive'), |
| | 373 | (r'^/articles/(\d{4})/(\d{2})/(\d+)/$', 'mysite.views.article_detail'), |
| | 374 | ) |
| | 375 | |
| | 376 | Ecco come potrebbe apparire un URLconf per l'esempio ``Reporter``/``Article`` |
| | 377 | esposto in precedenza:: |
| | 378 | |
| | 379 | from django.conf.urls.defaults import * |
| | 380 | |
| | 381 | urlpatterns = patterns('', |
| | 382 | (r'^/articles/(\d{4})/$', 'mysite.views.year_archive'), |
| | 383 | (r'^/articles/(\d{4})/(\d{2})/$', 'mysite.views.month_archive'), |
| | 384 | (r'^/articles/(\d{4})/(\d{2})/(\d+)/$', 'mysite.views.article_detail'), |
| | 385 | ) |
| | 386 | |
| | 387 | |
| | 388 | .. |
| | 389 | The code above maps URLs, as simple regular expressions, to the location of |
| | 390 | Python callback functions ("views"). The regular expressions use parenthesis to |
| | 391 | "capture" values from the URLs. When a user requests a page, Django runs |
| | 392 | through each pattern, in order, and stops at the first one that matches the |
| | 393 | requested URL. (If none of them matches, Django calls a special-case 404 view.) |
| | 394 | This is blazingly fast, because the regular expressions are compiled at load |
| | 395 | time. |
| | 396 | |
| | 397 | Questo codice associa gli URL, espressi come semplici espressioni regolari, a |
| | 398 | funzioni di callback scritte in Python (chiamate "view"). La "cattura" dei |
| | 399 | valori specificati assieme agli URL avviene usando parentesi nelle espressioni |
| | 400 | regolari. Quando un utente richiede una pagina, Django scorre ogni espressione |
| | 401 | regolare, rispettando l'ordine di presentazione, interrompendo la ricerca non |
| | 402 | appena viene trovato un URL in grado di soddisfare l'espressione regolare (se non |
| | 403 | vengono trovate corrispondenze si fa ricorso ad una view speciale di tipo 404). |
| | 404 | Le espressioni regolari sono compilate in fase di caricamento, perciò il procedimento |
| | 405 | di invocazione di una funzione in base all'URL richiesto risulta incredibilmente |
| | 406 | prestazionale. |
| | 407 | |
| | 408 | .. |
| | 409 | Once one of the regexes matches, Django imports and calls the given view, which |
| | 410 | is a simple Python function. Each view gets passed a request object -- |
| | 411 | which contains request metadata -- and the values captured in the regex. |
| | 412 | |
| | 413 | Quando una delle espressioni regolari corrisponde, Django importa e invoca la view |
| | 414 | associata, che semplicemente è una funzione Python. Ad ogni view viene |
| | 415 | passato un oggetto request -- contenente i metadati relativi alla richiesta -- |
| | 416 | e i valori catturati nell'espressione regolare. |
| | 417 | |
| | 418 | .. |
| | 419 | For example, if a user requested the URL "/articles/2005/05/39323/", Django |
| | 420 | would call the function ``mysite.views.article_detail(request, |
| | 421 | '2005', '05', '39323')``. |
| | 422 | |
| | 423 | Ad esempio, se un utente dovesse richiede l'URL "/articles/2005/05/39323/", Django |
| | 424 | invocherebbe la funzione ``mysite.views.article_detail(request, '2005', '05', '39323')``. |
| | 425 | |
| | 426 | .. |
| | 427 | Write your views |
| | 428 | ================ |
| | 429 | |
| | 430 | Scrivi le view |
| | 431 | ============== |
| | 432 | |
| | 433 | .. |
| | 434 | Each view is responsible for doing one of two things: Returning an |
| | 435 | ``HttpResponse`` object containing the content for the requested page, or |
| | 436 | raising an exception such as ``Http404``. The rest is up to you. |
| | 437 | |
| | 438 | Ogni view ha la responsabilità di restituire un oggetto ``HttpResponse`` |
| | 439 | contenente la pagina di risposta oppure sollevare un'eccezione come ``Http404``. |
| | 440 | Il resto dei compiti spetta a te. |
| | 441 | |
| | 442 | .. |
| | 443 | Generally, a view retrieves data according to the parameters, loads a template |
| | 444 | and renders the template with the retrieved data. Here's an example view for |
| | 445 | ``year_archive`` from above:: |
| | 446 | |
| | 447 | def year_archive(request, year): |
| | 448 | a_list = Article.objects.filter(pub_date__year=year) |
| | 449 | return render_to_response('news/year_archive.html', {'year': year, 'article_list': a_list}) |
| | 450 | |
| | 451 | Generalmente, una view ottiene i dati definiti dai parametri, carica un |
| | 452 | template (un modello della pagina che verrà restituita in seguito ad una |
| | 453 | richiesta) e popola il template con i dati ottenuti. La view ``year_archive`` |
| | 454 | potrebbe verosimilmente essere qualcosa di questo tipo:: |
| | 455 | |
| | 456 | def year_archive(request, year): |
| | 457 | a_list = Article.objects.filter(pub_date__year=year) |
| | 458 | return render_to_response('news/year_archive.html', {'year': year, 'article_list': a_list}) |
| | 459 | |
| | 460 | .. |
| | 461 | This example uses Django's template system, which has several powerful |
| | 462 | features but strives to stay simple enough for non-programmers to use. |
| | 463 | |
| | 464 | Il codice dell'esempio usa il meccanismo di gestione dei template offerto da |
| | 465 | Django, che pur esponendo funzionalità avanzate risulta sufficientemente |
| | 466 | semplice per poter essere usato anche da chi non è un programmatori. |
| | 467 | |
| | 468 | .. |
| | 469 | Design your templates |
| | 470 | ===================== |
| | 471 | |
| | 472 | Progetta i template |
| | 473 | =================== |
| | 474 | |
| | 475 | .. The code above loads the ``news/year_archive.html`` template. |
| | 476 | |
| | 477 | Nell'esempio, la vista ``year_archive`` carica il template |
| | 478 | ``news/year_archive.html``. |
| | 479 | |
| | 480 | .. |
| | 481 | Django has a template search path, which allows you to minimize redundancy among |
| | 482 | templates. In your Django settings, you specify a list of directories to check |
| | 483 | for templates. If a template doesn't exist in the first directory, it checks the |
| | 484 | second, and so on. |
| | 485 | |
| | 486 | Django minimizza le ridondanze tra i modelli di pagina implementando un percorso di |
| | 487 | ricerca dei template. Nelle impostazioni di configurazione puoi specificare una lista |
| | 488 | di directory dedicate ad ospitare i template. Se si cerca un template non presente |
| | 489 | nella prima directory, viene cercato nella seguente, e così via. |
| | 490 | |
| | 491 | .. |
| | 492 | Let's say the ``news/article_detail.html`` template was found. Here's what that |
| | 493 | might look like:: |
| | 494 | |
| | 495 | {% extends "base.html" %} |
| | 496 | |
| | 497 | {% block title %}Articles for {{ year }}{% endblock %} |
| | 498 | |
| | 499 | {% block content %} |
| | 500 | <h1>Articles for {{ year }}</h1> |
| | 501 | |
| | 502 | {% for article in article_list %} |
| | 503 | <p>{{ article.headline }}</p> |
| | 504 | <p>By {{ article.reporter.full_name }}</p> |
| | 505 | <p>Published {{ article.pub_date|date:"F j, Y" }}</p> |
| | 506 | {% endfor %} |
| | 507 | {% endblock %} |
| | 508 | |
| | 509 | Ipotizziamo che il template ``news/article_detail.html`` venga trovato. |
| | 510 | Potrebbe verosimilmente apparire così:: |
| | 511 | |
| | 512 | {% extends "base.html" %} |
| | 513 | |
| | 514 | {% block title %}Articoli del {{ year }}{% endblock %} |
| | 515 | |
| | 516 | {% block content %} |
| | 517 | <h1>Articoli del {{ year }}</h1> |
| | 518 | |
| | 519 | {% for article in article_list %} |
| | 520 | <p>{{ article.headline }}</p> |
| | 521 | <p>By {{ article.reporter.full_name }}</p> |
| | 522 | <p>Pubblicato in data {{ article.pub_date|date:"F j, Y" }}</p> |
| | 523 | {% endfor %} |
| | 524 | {% endblock %} |
| | 525 | |
| | 526 | .. |
| | 527 | Variables are surrounded by double-curly braces. ``{{ article.headline }}`` |
| | 528 | means "Output the value of the article's headline attribute." But dots aren't |
| | 529 | used only for attribute lookup: They also can do dictionary-key lookup, index |
| | 530 | lookup and function calls. |
| | 531 | |
| | 532 | Le variabili sono circondate da coppie di parentesi graffe. ``{{article.headline }}`` |
| | 533 | significa "Restituisci il valore dell'attributo headline |
| | 534 | di article". Le parentesi graffe non vengono utilizzate esclusivamente per il lookup |
| | 535 | degli attributi, ma anche per ottenere i valori corrispondenti a chiavi di |
| | 536 | dizionario, per il lookup basato su indici o per richiamare funzioni. |
| | 537 | |
| | 538 | .. |
| | 539 | Note ``{{ article.pub_date|date:"F j, Y" }}`` uses a Unix-style "pipe" (the "|" |
| | 540 | character). This is called a template filter, and it's a way to filter the value |
| | 541 | of a variable. In this case, the date filter formats a Python datetime object in |
| | 542 | the given format (as found in PHP's date function; yes, there is one good idea |
| | 543 | in PHP). |
| | 544 | |
| | 545 | Nota come le "pipe" (il carattere "|") in stile Unix vengono utilizzate in |
| | 546 | ``{{ article.pub_date|date:"F j, Y" }}``. Questo particolare costrutto è un filtro |
| | 547 | di template, e viene usato per filtrare il contenuto di una variabile. In |
| | 548 | questo caso, il filtro ``date`` formatta un oggetto ``datetime`` di Python nel |
| | 549 | formato specificato (come descritto nella funzione ``date`` di PHP; ebbene sì, |
| | 550 | c'è una buona idea in PHP). |
| | 551 | |
| | 552 | .. |
| | 553 | You can chain together as many filters as you'd like. You can write custom |
| | 554 | filters. You can write custom template tags, which run custom Python code behind |
| | 555 | the scenes. |
| | 556 | |
| | 557 | Puoi concatenare un numero arbitrario di filtri, puoi scrivere filtri |
| | 558 | personalizzati e, se hai la necessità di eseguire codice Python nel template in |
| | 559 | modo trasparente, puoi anche personalizzare i tag di template. |
| | 560 | |
| | 561 | .. |
| | 562 | Finally, Django uses the concept of "template inheritance": That's what the |
| | 563 | ``{% extends "base.html" %}`` does. It means "First load the template called |
| | 564 | 'base', which has defined a bunch of blocks, and fill the blocks with the |
| | 565 | following blocks." In short, that lets you dramatically cut down on redundancy |
| | 566 | in templates: Each template has to define only what's unique to that template. |
| | 567 | |
| | 568 | Per finire, Django adotta il concetto di "ereditarietà dei tempate": è ciò che |
| | 569 | avviene in ``{% extends "base.html" %}``. Significa "Prima carica il |
| | 570 | template con nome 'base', dove sono definiti blocchi vuoti, poi riempi |
| | 571 | questi blocchi con altri blocchi". In sostanza, la ridondanza nei template viene |
| | 572 | drasticamente ridotta: ogni template deve definire solamente gli elementi che |
| | 573 | lo caratterizzano rendendolo unico. |
| | 574 | |
| | 575 | .. |
| | 576 | Here's what the "base.html" template might look like:: |
| | 577 | |
| | 578 | Il template "base.html" potrebbe essere:: |
| | 579 | |
| | 580 | <html> |
| | 581 | <head> |
| | 582 | <title>{% block title %}{% endblock %}</title> |
| | 583 | </head> |
| | 584 | <body> |
| | 585 | <img src="sitelogo.gif" alt="Logo" /> |
| | 586 | {% block content %}{% endblock %} |
| | 587 | </body> |
| | 588 | </html> |
| | 589 | |
| | 590 | .. |
| | 591 | Simplistically, it defines the look-and-feel of the site (with the site's logo), |
| | 592 | and provides "holes" for child templates to fill. This makes a site redesign as |
| | 593 | easy as changing a single file -- the base template. |
| | 594 | |
| | 595 | Evitando spiegazioni prolisse, questo template definisce l'aspetto |
| | 596 | comune del sito (il look-and-feel) con il logo, emette a disposizione aree vuote che |
| | 597 | saranno riempite da template figli. Il restyling di un sito si riduce al ritocco di |
| | 598 | un singolo file -- il template base. |
| | 599 | |
| | 600 | .. |
| | 601 | It also lets you create multiple versions of a site, with different base |
| | 602 | templates, while reusing child templates. Django's creators have used this |
| | 603 | technique to create strikingly different cell-phone editions of sites -- simply |
| | 604 | by creating a new base template. |
| | 605 | |
| | 606 | L'ereditarietà dei template consente anche di creare differenti versioni di un |
| | 607 | sito usando template di base diversi che condividono gli stessi template |
| | 608 | figli. Gli autori di Django hanno usato questa tecnica per creare edizioni di |
| | 609 | siti adatte alla visualizzazione su telefoni cellulari, semplicemente creando |
| | 610 | un nuovo template di base. |
| | 611 | |
| | 612 | .. |
| | 613 | Note that you don't have to use Django's template system if you prefer another |
| | 614 | system. While Django's template system is particularly well-integrated with |
| | 615 | Django's model layer, nothing forces you to use it. For that matter, you don't |
| | 616 | have to use Django's database API, either. You can use another database |
| | 617 | abstraction layer, you can read XML files, you can read files off disk, or |
| | 618 | anything you want. Each piece of Django -- models, views, templates -- is |
| | 619 | decoupled from the next. |
| | 620 | |
| | 621 | Sappi che non sei obbligato ad usare il sistema di template di Django, se ne |
| | 622 | preferisci altri. Nonostante esso sia particolarmente ben integrato nel framework, |
| | 623 | nulla ti forza ad usarlo. Per lo stesso motivo non ti è nemmeno imposto l'obbligo |
| | 624 | di usare le API di Django per l'interfacciamento ai database. Puoi usare un altro |
| | 625 | sistema di astrazione per database, puoi leggere file XML, file su disco o fare |
| | 626 | qualsiasi altra cosa sia nelle tue intenzioni. Ogni frammento di Django -- i modelli, |
| | 627 | le view, i template -- è indipendente dal seguente. |
| | 628 | |
| | 629 | .. |
| | 630 | This is just the surface |
| | 631 | ======================== |
| | 632 | |
| | 633 | Questo è solo un assaggio |
| | 634 | ========================= |
| | 635 | |
| | 636 | .. |
| | 637 | This has been only a quick overview of Django's functionality. Some more useful |
| | 638 | features: |
| | 639 | |
| | 640 | * A caching framework that integrates with memcached or other backends. |
| | 641 | * A syndication framework that makes creating RSS and Atom feeds as easy as |
| | 642 | writing a small Python class. |
| | 643 | * More sexy automatically-generated admin features -- this overview barely |
| | 644 | scratched the surface. |
| | 645 | |
| | 646 | Il contenuto di questo documento è soltanto una rapida panoramica di quelle che |
| | 647 | sono le funzionalità di Django. Alcune altre caratteristiche, ancora più utili, |
| | 648 | sono: |
| | 649 | |
| | 650 | * Un sistema di caching che si integra con svariati backend, tra cui |
| | 651 | memcached. |
| | 652 | * Un sistema di syndication che rende la creazione di feed RSS e Atom |
| | 653 | un'operazione tanto semplice da essere paragonabile alla scrittura |
| | 654 | di una piccola classe Python. |
| | 655 | * Funzionalità di amministrazione generate automaticamente -- in questa |
| | 656 | introduzione non si è andati oltre la superficie. |
| | 657 | |
| | 658 | .. |
| | 659 | The next obvious steps are for you to `download Django`_, read `the tutorial`_ |
| | 660 | and join `the community`_. Thanks for your interest! |
| | 661 | |
| | 662 | .. _download Django: http://www.djangoproject.com/download/ |
| | 663 | .. _the tutorial: http://www.djangoproject.com/documentation/tutorial1/ |
| | 664 | .. _the community: http://www.djangoproject.com/community/ |
| | 665 | |
| | 666 | Ora per te, i prossimi passi logici saranno `scaricare Django`_, leggere |
| | 667 | `il tutorial`_ e diventare parte della `comunità`_. |
| | 668 | Grazie per l'interesse mostrato! |
| | 669 | |
| | 670 | .. _scaricare Django: http://www.djangoproject.com/download/ |
| | 671 | .. _il tutorial: http://www.djangoproject.com/documentation/tutorial1/ |
| | 672 | .. _comunità: http://www.djangoproject.com/community/ |
| | 673 | |
| | 674 | }}} |