User Tools

Site Tools


doc:appunti:prog:django

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
doc:appunti:prog:django [2011/06/26 11:13] – [Mettere i dati nella vista] niccolodoc:appunti:prog:django [2011/06/28 09:15] (current) – [Mettere i dati nella vista] niccolo
Line 165: Line 165:
         </html>         </html>
     ''' % (     ''' % (
-        u'Balance'+        u'Titolo della vista'
     )     )
     return HttpResponse(output)     return HttpResponse(output)
Line 187: Line 187:
 Invece di includere il codice HTML direttamente nella vista (funzione Python) si utilizza il sistema dei **template**. Invece di includere il codice HTML direttamente nella vista (funzione Python) si utilizza il sistema dei **template**.
  
-Nella directory radice del progetto si crea la sottodirectory **''templates''** e nel file **''settings.py''** si definisce la **''TEMPLATE_DIRS''**:+Nella directory radice del progetto si crea la sottodirectory **''templates''** e nel file **''settings.py''** si definisce la **''TEMPLATE_DIRS''** (controllare se il modulo os.path è già incluso):
  
 <code python> <code python>
 +import os.path
 +
 TEMPLATE_DIRS = ( TEMPLATE_DIRS = (
     os.path.join(os.path.dirname(__file__), 'templates),     os.path.join(os.path.dirname(__file__), 'templates),
Line 213: Line 215:
 from django.template.loader import get_template from django.template.loader import get_template
  
-def balance(request): +def my_view(request): 
-    template = get_template('balance.html')+    template = get_template('my_view.html')
     variables = Context({     variables = Context({
         'page_title': u'Titolo della vista',         'page_title': u'Titolo della vista',
Line 221: Line 223:
     output = template.render(variables)     output = template.render(variables)
     return HttpResponse(output)     return HttpResponse(output)
 +</code>
 +
 +==== Visualizzazione e aggregazione dei dati ====
 +
 +Nel codice della **view** è possibile accedere ai dati (i **model**) sfruttando anche le relazioni tra essi (le //foreign key// delle tabelle del database). È possibile anche usare funzioni di aggregazione.
 +
 +Ecco un esempio di una vista dell'applicazione **spese** (**''my_project/spese/views.py''**), che accede ai dati del modello **''User''** e del modello correlato **''Expense''** (sono tabelle correlate). Nella vista si aggiunge un attributo al modello ''User'', aggregando per ogni ''User'' il campo ''amount'' del modello ''Expense'', calcolando la **''Sum''** e il **''Count''**:
 +
 +<code python>
 +from django.http import HttpResponse
 +from django.template import Context
 +from django.template.loader import get_template
 +
 +from django.db.models import Sum, Count
 +
 +from django.contrib.auth.models import User
 +#from spese.models import Expense
 +
 +def balance(request):
 +
 +    users = User.objects.all()
 +
 +    max_expense = 0
 +    for user in users:
 +        user.aggr = user.expense_set.aggregate(Count('amount'), Sum('amount'))
 +        if user.aggr['amount__sum'] > max_expense:
 +            max_expense = user.aggr['amount__sum']
 +    for user in users:
 +        user.balance = user.aggr['amount__sum'] - max_expense
 +
 +    template = get_template('balance.html')
 +    variables = Context({
 +        'page_title':    u'Bilancio spese',
 +        'users':         users,
 +        'max_expense':   max_expense
 +    })
 +    output = template.render(variables)
 +    return HttpResponse(output)
 +</code>
 +
 +Ecco infine il template **''my_project/templates/balance.html''** che provvede ad impaginare i dati:
 +
 +<code html>
 +<html>
 +<body>
 +  <h1>{{page_title}}</h1>
 +  {% if users %}
 +    <table border="1" cellspacing="0">
 +      <tr>
 +        <th>Persona</th>
 +        <th>Numero spese</th>
 +        <th>Somma spesa</th>
 +        <th>Bilancio</th>
 +      </tr>
 +      {% for user in users %}
 +        <tr>
 +          <td>{{user.username}}</td>
 +          <td>{{user.aggr.amount__count}}</td>
 +          <td>{{user.aggr.amount__sum}}</td>
 +          <td>{{user.balance}}</td></tr>
 +      {% endfor %}
 +    </table>
 +  {% else %}
 +    <p>No users found.</p>
 +  {% endif %}
 +</body>
 +</html>
 </code> </code>
 ===== Webserver di test ===== ===== Webserver di test =====
doc/appunti/prog/django.1309079592.txt.gz · Last modified: 2011/06/26 11:13 by niccolo