Render HTML In Django Without A Template

Render HTML In Django Without A Template

Is it possible to render HTML using Django if you are not using a templating system? Yes, it is possible to do this. In order to render HTML without a template in Django, we’ll need to manually build up a string of HTML and send that to the browser as an HttpResponse. It’s not really ideal to render HTML this way, but this is a good exercise to really understand how Django processes requests, responses, and rendering of HTML.


Creating An HTML Homepage

The goal of this step for this Django application is to add a homepage where all of the goals are listed in an unordered list. Each item in the list should be wrapped in an anchor tag in order to make it clickable to view more information. So first, we need to add a route that represents the homepage in urls.py.

C:\python\djangoprojects\myproject\goals\urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.homepage),
    path('<int:timeframe>', views.goals_by_int_timeframe),
    path('<str:timeframe>', views.goals_by_timeframe, name='namedurl'),
]

Define Homepage View

This newly added route points to the homepage function in views.py. We can add this function now.

C:\python\djangoprojects\myproject\goals\views.py

from django.shortcuts import redirect, render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse

# dictionary data store
goals = {
    'daily': 'Learn Something New',
    'weekly': 'Take a day off',
    'monthly': 'Complete a creative course'
}


def homepage(request):
    goal_list = '<html><body><ul>'
    for goal in goals.keys():
        href = reverse('namedurl', args=[goal])
        goal_list += f'<li><a href="{href}">{goal}</a></li>'
    goal_list += '</ul></body></html>'
    return HttpResponse(goal_list)


def goals_by_int_timeframe(request, timeframe):
    timeframes = list(goals.keys())
    redirect_to = timeframes[timeframe - 1]
    named_redirect = reverse('namedurl', args=[redirect_to])
    return HttpResponseRedirect(named_redirect)


def goals_by_timeframe(request, timeframe):
    goal = goals[timeframe]
    return HttpResponse(goal)

How The homepage() Function Works

In the previous handful of tutorials, we have been responding to requests with responses that contained simple strings. This has demonstrated how a request and response cycle works in Django, but a better way to do this is by rendering HTML to the browser. So what this homepage() function does is construct a Python String that is made up of valid HTML which a Web Browser can render. The first step is to create a variable named goal_list. We begin by assigning the opening HTML tags of <HTML>, <body>, and <ul>. Next, we use a Python For Loop to build up all of the keys of the goals dictionary inside of HTML <li> elements. We also made use of the Django reverse() function to calculate the href value to use for the namedurl in the application. Once the HTML is suitably built up, it is returned in an HttpResponse to the web browser. Taking the very simple application for a test run shows that it is working great.