UNC BACS 350

Web Apps with Python/Django

Logo

Lesson 11 - List View

LEARN

Week 4 - Data

ListView

templates/hero_list.html

<h1>Superhero Gallery</h1>
<ul>
  {% for hero in object_list %}
    <li>{{ hero.name }}</li>
  {% endfor %}
</ul>

hero/views.py

from django.views.generic import ListView

class HeroListView(ListView):
    model = Hero
    template_name = 'hero_list.html'

config/urls.py

from django.urls import path
from hero.views import HeroListView

urlpatterns = [
    path('hero/', HeroListView.as_view()),
]

BUILD - ListView

Aliases

Define command shortcuts to save typing

$ alias l='ls -al'

$ alias s='git status'

$ alias pull='git pull'

$ alias dj='python manage.py'

$ function d {
        cd $1 && l
    }

ListView - Template

templates/hero_list.html

<ul>
  {% for hero in object_list %}
    <li>{{ hero.name }}</li>
  {% endfor %}
</ul>

ListView - View

hero/views.py

class HeroListView(ListView):
    model = Hero
    template_name = 'hero_list.html'

ListView - URL

config/urls.py

urlpatterns = [
    path('hero/', HeroListView.as_view()),
]

ListView - Test

BUILD - DetailView

DetailView - Template

templates/hero_detail.html

<ul>
  {% for hero in object_list %}
    <li>{{ hero.name }}</li>
  {% endfor %}
</ul>

DetailView - View

hero/views.py

class HeroDetailView(TemplateView):
    model = Hero
    template_name = 'hero_detail.html'

DetailView - URL

config/urls.py

urlpatterns = [
    path('hero/', HeroListView.as_view()),
    path('hero/<int:pk>', HeroDetailView.as_view()),
]

DetailView - Test

BUILD - Tests

Django Tests

hero/tests.py

from django.test import TestCase

class Tests(TestCase):
    def test_home_page_status_code(self):
        response = self.client.get('/')
        self.assertEqual(response.status_code, 200)

Run all tests

$ python manage.py test