7.2. Views Function Based

  • Function Based Views (FBV) are a way to define views as functions.

7.2.1. Example

from django.http import Http404
from django.shortcuts import render
from shop.models import Product

def product_detail(request, product_id):
    try:
        p = Product.objects.get(pk=product_id)
    except Product.DoesNotExist:
        raise Http404("Product does not exist")
    return render(request, 'shop/product-detail.html', {'product': p})

7.2.2. HttpResponse

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

7.2.3. HttpResponseNotFound

from django.http import HttpResponse, HttpResponseNotFound

def my_view(request):
    # ...
    if foo:
        return HttpResponseNotFound('<h1>Page not found</h1>')
    else:
        return HttpResponse('<h1>Page was found</h1>')

7.2.4. Status Code

from django.http import HttpResponse

def my_view(request):
    # do something
    return HttpResponse(status=201)

7.2.5. Assignments

# FIXME: Write tests

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Django View FBV
# - Difficulty: easy
# - Lines: 6
# - Minutes: 5

# %% English
# 0. Use `myproject.shop`
# 1. Create function based view `product_list()`
# 2. View must return HTML with list of all products
# 3. Use `django.shortcuts.render` to render template
# 4. Create `shop/product-list.html` template
# 5. Register view in `urls.py` with name `shop-product-list-fbv`

# %% Polish
# 0. Użyj `myproject.shop`
# 1. Stwórz widok oparty o funkcję `product_list()`
# 2. Widok ma zwrócić HTML z listą wszystkich produktów
# 3. Użyj `django.shortcuts.render` do renderowania szablonu
# 4. Stwórz szablon `shop/product-list.html`
# 5. Zarejestruj widok w `urls.py` z nazwą `shop-product-list-fbv`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python 3.10+ required'
"""

# Required for Django to work
import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
import django; django.setup()

...

# FIXME: Write tests

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Django View FBV
# - Difficulty: easy
# - Lines: 6
# - Minutes: 5

# %% English
# 0. Use `myproject.shop`
# 1. Create function based view `product_details()`
# 2. View must return HTML with details of the product
# 3. Primary Key of the product will be passed in `pk` parameter
# 4. Use `django.shortcuts.render` to render template
# 5. Create `shop/product-detail.html` template
# 6. Register view in `urls.py` with name `shop-product-details-fbv`

# %% Polish
# 0. Użyj `myproject.shop`
# 1. Stwórz widok oparty o funkcję `product_details()`
# 2. Widok ma zwrócić HTML z detalami produktu
# 3. Primary Key produktu zostanie przekazany w parametrze `pk`
# 4. Użyj `django.shortcuts.render` do renderowania szablonu
# 5. Stwórz szablon `shop/product-detail.html`
# 6. Zarejestruj widok w `urls.py` z nazwą `shop-product-details-fbv`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python 3.10+ required'
"""

# Required for Django to work
import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
import django; django.setup()

...