Home > Django > djangofantalega: model League

djangofantalega: model League

14 Novembre 2016

4 – Models: League

Creare il secondo Model dell’applicazione: League.
Una stagione (Season) può avere più Leghe, ad es. Lega e Champions
quindi trattasi di relazione Season-League: one-to-many.

season_league

Aggiungere nel file fantalega/models.py il model League:

from django.db import models
from fantalega.validators import validate_season_name


class Season(models.Model):
    name = models.CharField(max_length=9, validators=[validate_season_name])

    def __unicode__(self):
        return self.name


class League(models.Model):
    name = models.CharField(max_length=32)
    budget = models.IntegerField()
    max_trades = models.IntegerField()
    max_goalkeepers = models.IntegerField()
    max_defenders = models.IntegerField()
    max_midfielders = models.IntegerField()
    max_forwards = models.IntegerField()
    rounds = models.IntegerField()
    offset = models.IntegerField()
    season = models.ForeignKey(Season, related_name='leagues')  # relationship

    def __unicode__(self):
        return self.name

Aggiornare il database inserendo la nuova tabella:

(venv) >python manage.py makemigrations
Migrations for 'fantalega':
  fantalega\migrations\0002_league.py:
    - Create model League

confermare con:

(venv) >python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, fantalega, log, sessions
Running migrations:
  Applying fantalega.0002_league... OK

Ora inserire qualche dato nel database:

(venv) >python manage.py shell
...
>>> from fantalega.models import Season, League
>>> s = Season.objects.get(pk=1)
>>> league = League.objects.create(name="lega 2016-2017", budget=500, max_trades=3, max_goalkeepers=3,
... max_defenders=8, max_midfielders=8, max_forwards=6, rounds=4, offset=2, season=s)
>>> cup = League.objects.create(name="Champions 2016-2017", budget=500, max_trades=3, max_goalkeepers=3,
... max_defenders=8, max_midfielders=8, max_forwards=6, rounds=2, offset=20, season=s)
>>> s.leagues.all()
<QuerySet [<League: lega 2016-2017>, <League: Champions 2016-2017>]>
>>> cup.season
<Season: 2016-2017>
>>> league.season
<Season: 2016-2017>
>>>

Sistemare l’interfaccia di admin per il model League:
file fantalega/admin.py:

# noinspection PyUnresolvedReferences
from django.contrib import admin
from .models import Season, League
from django.utils.html import format_html


class LeagueAdmin(admin.ModelAdmin):
    fieldsets = [(None, {'fields': ['name', 'budget', 'max_trades',
                                    'rounds', 'offset']}),
                 ('season', {'fields': ['season']}),
                 ('number of Players', {'fields': ['max_goalkeepers',
                                                   'max_defenders',
                                                   'max_midfielders',
                                                   'max_forwards']}),
                 ]

# Register your models here.
admin.site.register(Season)
admin.site.register(League, LeagueAdmin)

L’attributo fieldset è una lista di tuple, che permette di suddividere
visivamente, una serie di campi inerenti il model in oggetto.
Ogni tupla rappresenta una sezione ed è composta dal primo valore,
che rappresenta il nome della sezione (None, ‘season’, ‘number of players’),
da un dizionario che ha come chiave ‘fields’ che restituisce la
lista dei campi da visualizzare in tale sezione.

admin_league

Ora aggiungere gli urls inerenti League nel file fantalega\urls.py:

...
    # league urls
    url(r'^leagues/$', views.leagues, name='leagues'),
    url(r'^leagues/(?P<league_id>[0-9]+)/$', views.league_details,
        name='league_details'),
]

Aggiungere nel file fantalega\views.py le nuove viste ‘leagues’ e ‘league_details’:

...
from .models import Season, League  # League added
...


@login_required
def leagues(request):
    context = {'leagues': League.objects.order_by('-name')}
    return render(request, 'fantalega/leagues.html', context)


@login_required
def league_details(request, league_id):
    league = get_object_or_404(League, pk=int(league_id))
    context = {'league': league}
    return render(request, 'fantalega/league.html', context)

A questo punto mancano le template richiamate dalle viste:
fantalega/leagues.html

{% extends 'fantalega/base.html' %}

{% block content %}
        <h1><font color="green">List of LEAGUES</font></h1>
    {% if leagues %}
    <ul>
      {% for league in leagues %}
      <li><a href="{% url 'league_details' league.id %}">{{ league.name }} -</a>
       {{ league.season.name }}</li>
      {% endfor %}
    </ul>
    {% else %}
      <font color="red"><b>No league found.</b></font>
    {% endif %}
{% endblock %}

e fantalega/league.html

{% extends 'fantalega/base.html' %}
{% load bootstrap3 %}

{% block content %}
		<h1><font color="green">{{ league.name }}</font></h1>

    <table class="table table-striped" width="100%">
      <tr>
          <th>budget</th>
          <th>max trade remaining</th>
          <th>max goalkeepers</th>
          <th>max defenders</th>
          <th>max midfielders</th>
          <th>max forwards</th>
          <th>rounds to do</th>
          <th>offset</th>
      </tr>
      <tr>
              <td>{{ league.budget }}</td>
              <td>{{ league.max_trades }}</td>
              <td>{{ league.max_goalkeepers }}</td>
              <td>{{ league.max_defenders }}</td>
              <td>{{ league.max_midfielders }}</td>
              <td>{{ league.max_forwards }}</td>
              <td>{{ league.rounds }}</td>
              <td>{{ league.offset }}</td>
      </tr>
    </table>

	<div id="container" style="width:100%;">
		<div id="left" style="float:left; width:50%;">
			<b><font color="orange">League Teams:</font></b>
			<ul>
			{% if teams %}
				{% for team in teams %}
				  <li><a href="{% url 'team_details' league.id team.id %}">
					{{ team.name }}</a></li>
				{% endfor %}

				{% if user.is_staff %}
				<form action="#" method="get">
				  <input type="submit" class="btn" value="Start Auction"
						name="auction">
				  <input type="submit" class="btn" value="Create Calendar"
						name="calendar">
				</form>
				{% endif %}
			{% else %}
			  <b><font color="red">no team created yet</font></b>
			{% endif %}
			</ul>
		</div>

		<div id="right" style="float:right; width:50%;">
			<b><font color="orange">Evaluation uploaded</font></b>
			<ul>
			  {% for day in days %}
			  <li><a href="{% url 'vote' league.id day %}">
				  Evaluation day: {{ day }}</a></li>
			  {% endfor %}
			</ul>
			{% if user.is_staff %}
			  <form action="#" method="get">
				<input type="submit" class="btn" value="Upload votes"
					  name="upload votes">
			  </form>
			{% endif %}
		  <form action="#" method="get">
			{% if league.matches %}
				<input type="submit" class="btn" value="view Calendar"
					  name="matches">
				<input type="submit" class="btn" value="view Chart"
					  name="chart">
				<input type="submit" class="btn" value="view trades"
					  name="trades">
			{% endif %}
		  </form>
		</div>
    </div>
{% endblock %}

In questa template sono contemplati degli if-tag che controllano se siano presenti o
meno degli oggetti (Team o Match) in modo da rendere visibili o meno certi pulsanti.
Nella situazione attuale, questi pulsanti non sono visibili non avendo ancora
creato il model Team.

La pagina Leagues è di uso comune quindi aggiungere un link nella template base,
nella navbar.

...
      {% if user.is_staff %}
        <div class="navbar-header">
          <a class="navbar-brand" href="{% url 'admin:index' %}">
              <font color="red">Admin</font></a></div>
      {% endif %}
      <div class="navbar-header">
        <a class="navbar-brand" href="{% url 'seasons' %}">Seasons</a></div>
      <div class="navbar-header">
        <a class="navbar-brand" href="{% url 'leagues' %}">Leagues</a></div>
    {% endif %}
...

Salvare gli avanzamenti su github:

git add --all
git commit -m "League added"
git push -u origin master

articoli precedenti
0 – indice
1 – Virtualenv e Git
2 – Models: Season
3 – Admin: Login e Logout

articoli successivi
5 – Models: Team
6 – Models: Match
7 – Models: Player
8 – Asta
9 – Models: Lineup
10 – Models: Trade
11 – Asta di riparazione
12 – Classifica

Categorie:Django Tag:
I commenti sono chiusi.