UNC BACS 350

Web Apps with Python/Django

Logo

Lesson 6 - Static Server

LEARN

Sensei Login

Class-based views

TemplateView template

templates/hulk.html

<h1>Hulk Profile</h1>

<img src="hulk.jpg" alt="Hulk">

TemplateView views.py

views.py

from django.views.generic import TemplateView

class HulkView(TemplateView):
    template_name = 'hulk.html'

TemplateView urls.py

urls.py

from django.urls import path
from django.views.generic import HulkView, WidowView

urlpatterns = [
    path('hulk', HulkView.as_view()),
]

BUILD

Templates with Images

templates/hulk.html

<h1>Hulk Profile</h1>
<img src="hulk.jpg" alt="Hulk">

templates/black_widow.html

<h1>Black Widow</h1>
<img src="black_widow.jpg" alt="Hulk">

urls.py

from django.urls import path
from django.views.generic import HulkView, WidowView

urlpatterns = [
    path('hulk', HulkView.as_view()),
    path('black_widow', WidowView.as_view()),
]

pages/views.py

from django.views.generic import TemplateView

class HulkView(TemplateView):
    template_name = 'hulk.html'

class WidowView(TemplateView):
    template_name = "black_widow.html"

templates/

hulk.jpg
black_widow.jpg

Pages may Contain Images

Add Custom Django Views

static/images/

hulk.jpg
black_widow.jpg

templates/hulk.html

<h1>Hulk Profile</h1>
<img src="/static/images/hulk.jpg" alt="Hulk">

templates/black_widow.html

<h1>Black Widow</h1>
<img src="/static/images/black_widow.jpg" alt="Hulk">

settings.py

Images, CSS, Javascript

Add Data to Django Views

templates/hero.html

<h1>Hero: {{ hero }}</h1>
<img src="/static/images/{{ hero }}.jpg" alt="{{ hero }}">

Data as dictionary

Define what goes in the variable slots

{
    'hero': 'hulk', 
}

{
    'hero': 'black_widow', 
}

Hero View

pages/views.py

 class HulkView(TemplateView):
    template_name = 'hero.html'

    def get_context_data(self, **kwargs):
        return { 'hero': 'hulk' }


 class WidowView(TemplateView):
    template_name = "hero.html"

    def get_context_data(self, **kwargs):
        return { 'hero': 'black_widow' }

Demo Code in Github

Exercise