Skip to content

Fetch data from the database to response

Serhii Horodilov edited this page Feb 21, 2024 · 3 revisions

Table of Contents

Getting started

git checkout bp-orm

Guide

Update tasks app views

tasks/views.py

"""
Tasks application views

"""

import uuid

from django.http.request import HttpRequest
from django.http.response import Http404, HttpResponse
from django.shortcuts import get_object_or_404, redirect, render

from tasks.models import TaskModel


def task_list_view(request: HttpRequest) -> HttpResponse:
    """
    Handle requests to tasks list

    """

    ctx = {
        "object_list": TaskModel.objects.all(),
    }

    return render(request, "tasks/task_list.html", ctx)


def task_detail_view(request: HttpRequest, pk: uuid.UUID) -> HttpResponse:
    """
    Handle requests to task details

    """

    try:
        task = TaskModel.objects.get(pk=pk)
    except TaskModel.DoesNotExist:
        raise Http404

    ctx = {
        "object": task,
    }

    return render(request, "tasks/task_detail.html", ctx)


def task_create_view(request: HttpRequest) -> HttpResponse:
    """
    Handle requests to create a new task instance

    """

    return render(request, "tasks/task_form.html")


def task_update_view(request: HttpRequest, pk: uuid.UUID) -> HttpResponse:
    """
    Handle requests to update an existing task instance

    """

    get_object_or_404(TaskModel, pk=pk)

    return render(request, "tasks/task_form.html")


def task_delete_view(request: HttpRequest, pk: uuid.UUID) -> HttpResponse:
    """
    Handle requests to delete an existing task instance

    """

    get_object_or_404(TaskModel, pk=pk)

    return redirect("tasks:list")

Update template tags

This section requires Render HTML templates to response.

tasks/templatetags/tasks.py

"""
Tasks application templatetags

"""

import datetime
from typing import Any, Dict

from django import template
from django.contrib.humanize.templatetags import humanize
from django.utils import timezone

register = template.Library()


@register.filter(name="row_completed_mark")
def get_row_completed_mark(completed: bool) -> str:
    """
    Return row completed marker based on instance completed status value

    :param completed: task instance completed status
    :type completed: bool

    :return: rom completed marker
    :rtype: str

    """
    if completed:
        return "data-task-completed=true"

    return "data-task-completed=false"


@register.filter(name="is_within_days")
def get_task_humanize_timestamp(value: datetime.datetime, days: int = 7) -> str:
    """
    Return human-readable timestamp

    :param value: timestamp
    :type value: :class: `datetime.datetime`
    :param days: number of days in threshold, defaults to 7
    :type days: int

    :return: human-readable timestamp, transformed with humanize app
    :rtype: str

    If given timestamp is within days from current time range, it will
    be transformed using ``naturaltime`` filter. Otherwise, ``naturalday``
    filter will be used.

    """

    if not timezone.is_aware(value):
        # make sure ``value`` is timezone-aware
        value = timezone.make_aware(value, timezone.get_current_timezone())

    if timezone.now() - value <= datetime.timedelta(days=days):
        return humanize.naturaltime(value)

    return humanize.naturalday(value)


@register.inclusion_tag("tasks/_task_tr.html", takes_context=True)
def task_row(context: Dict[str, Any], obj):
    # TODO: GH-78
    return {"object": obj}

Changes

  1. Full change log