Le viste in Django

Elenco degli oggetti di un modello

Per creare una vista che elenchi gli oggetti di un modello occorre:

  • definire la vista nel file didattica/views.py
    from django.views.generic.list import ListView
    from .models import Professor
    class ProfessorListView(ListView):
      model = Professor
    
  • definirne il template che di default andrà nel file didattica/templates/didattica/professor_list.html
<!DOCTYPE html>
<html>
<body>
<h1>Professors</h1>
<ul>
{% for prof in object_list %}
    <li>
<a href="{% url 'professor-detail' prof.slug %}">{{ prof.slug }}</a> - {{ prof.first_name }} {{ prof.last_name }}
    </li>
{% empty %}
    <li>No professors yet.</li>
{% endfor %}
</ul>
</body>
</html>
  • definirne l'url attraverso cui accedervi nel file didattica/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^professors/$', views.ProfessorListView.as_view()),
]

Per fare sì che Django recuperi gli url della applicazione didattica occorre includerli nel file principale master/urls.py che sarà quindi come segue

from django.conf.urls import url, include
from django.contrib import admin
from didattica.views import home

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('didattica.urls')),
    url(r'^$', home, name='home'),
]

Dettaglio di un oggetto del modello

  • Definizione della vista nel file didattica/views.py
from django.views.generic.detail import DetailView
class ProfessorDetailView(DetailView):
    model = Professor
  • Definizione del template nel file didattica/templates/didattica/professor_detail.html
<!DOCTYPE html>
<html>
<body>
<h1>{{ object.slug }}</h1>
<p>First Name: {{ object.first_name }}</p>
<p>Last Name: {{ object.last_name }}</p>
</body>
</html>
  • Definizione della vista nel filel didattica/urls.py
urlpatterns = [
    url(r'^professors/$', views.ProfessorListView.as_view()),
    url(r'^professors/(?P<slug>[-\w]+)/$', views.ProfessorDetailView.as_view(), name='professor-detail'),
]

results matching ""

    No results matching ""