UNC BACS 350

Web Apps with Python/Django

Logo

Carousel View Design Pattern

Overview

Goals

Add an image carousel to web pages.

Encapsulate common logic for reuse to build views in 5 minutes.

Use Bootstrap to create consistent appearance.

Use Partial Template "carousel.html" to organize your code logic.

Pass in data as a dictionary for images and labels.

Steps

Data

Reading a Data

python def carousel_data(): return [ dict(image_url="https://source.unsplash.com/random/1200x800?bear", label="Bear", active="active"), dict(image_url="https://source.unsplash.com/random/1200x800?forest", label="Forest"), dict(image_url="https://source.unsplash.com/random/1200x800?ocean", label="Ocean"), dict(image_url="https://source.unsplash.com/random/1200x800?flower", label="Flower"), ]

Template

templates/carousel.html

```html

```

Views

workshop/views.py

```python class CarouselView(TemplateView): template_name = 'carousel.html'

def get_context_data(self, **kwargs):
    carousel = carousel_data()
    return dict(title='Carousel View', carousel=carousel)

```

URL Routes

workshop/urls.py

python urlpatterns = [ path('carousel', CarouselView.as_view(), name='carousel'), ]

Tests

workshop/tests.py

```python from django.test import TestCase

class ViewTest(TestCase):

def test_carousel_view(self):
    response = self.client.get('/carousel')
    self.assertContains(response, 'Ocean')

```