How to Render HTML with Context Variable as Parameter to Pass to HTML File in Django Application

Posted on

Introduction

This article will be focus on continuing the progress from the previous article. The previous article is exist in ‘How to Render HTML with Base Template HTML and Printing the Content of the HTML file in Django Application‘. In that article, there is a specific content which only exist in a certain HTML file. As an addition for a demonstration in this article, there will be another feature. A feature which is very useful for the Django application. It allow to pass the value from Django application’s script to the HTML file. As for the HTML file, it acts as the view or the front-end of the Django application. So, as usual in order to be able to do that, just prepare the following :

  1. First of all, python tool is necessary. It is exist in several articles in ‘How to Install Python in Microsoft Windows‘ or ‘How to Install Python in Microsoft Windows 11‘.

  2. Second step, pip tool is also is necessary. As an additional information for how to do it, just look in ‘How to Install pip in Microsoft Windows‘ or ‘How to Install pip in Microsoft Windows 11

  3. Continue on to the third step, it is optional to have a python virtual environment. Otherwise just use the existing pip tool which is using the installed python to install Django library. For creating a python virtual environment, just check ‘How to Create a Python Virtual Environment with a specific version of Python in Microsoft Windows and How to Specify Specific Python Version for Creating a Virtual Python Environment in Microsoft Windows‘.

  4. Soon after, just perform the fourth step. After having a Django library exist in the local device just create a Django project. Check an article as a reference in ‘How to Create Django Project in Microsoft Windows using Command Line‘. Following after, create a Django application. Just use the article in ‘How to Create a Django Application inside a Django Project in Microsoft Windows‘ to create a Django application.

Actually, the result of the above preparation will be a Django project where a Django application exist inside in it. Below are the structure of the folder :

(env) C:\django\myproject>tree /A
Folder PATH listing for volume Windows-SSD
Volume serial number is CA30-19A4
C:.
+---myapp
| +---migrations
| | \---__pycache__
| +---templates
| | \---myapp
| \---__pycache__
\---myproject
\---__pycache__

(env) C:\django\myproject>
(env) C:\django\myproject> cd myapp
(env) C:\django\myproject\myapp>tree /F
Folder PATH listing for volume Windows-SSD
Volume serial number is CA30-19A4
C:.
│ admin.py
│ apps.py
│ models.py
│ urls.py
│ views.py
│ __init__.py
│
├───migrations
│ │ __init__.py
│ │
│ └───__pycache__
│ __init__.cpython-310.pyc
│
├───templates
│ └───myapp
│ index.html
│
└───__pycache__
__init__.cpython-310.pyc

(env) C:\django\myproject\myapp>

How to Pass Value using Variable to HTML File in Django Application

As for this part, just continue the step from the previous part. It is a part where the focus will be about showing how to pass value using variable to a HTML file which exist in the Django application. Below are the steps in sequences :

  1. Getting into the first step, declare the URL address to execute the process. In other words, an URL address which is going to represent the function for further execution. It will pass a certain value from the Django application so that it will appear in the HTML page along with the content of the HTML file inside a block content. Still, the HTML page will also use the base template HTML page.  Add the following line in the ‘urls.py’ exist in the ‘myapp’ folder representing Django application :

    path('index-render-html-with-value-from-content-parameter-and-block-content-using-base-template/', views.index_render_html_with_value_from_content_parameter_and_block_content_using_base_template, name="index-render-html-with-value-from-content-parameter-and-block-content-using-base-template"),

    Into the existing ‘urls.py’ file, just add the above line to the original content exist as follows :

    from django.contrib import admin
    from django.urls import path
    from . import views
    urlpatterns = [
        path('', views.index, name="index"),
        path('index-print-text/', views.index_print_text, name="index-print-text"),
        path('index-print-text-with-html-tags/', views.index_print_text_with_html_tags, name="index-print-text-with-html-tags"),
        path('index-render-plain-html/', views.index_render_plain_html, name="index-render-plain-html"),
        path('index-render-html-with-static-tags/', views.index_render_html_with_static_tags, name="index-render-html-with-static-tags"),
        path('index-render-html-with-base-template/', views.index_render_html_with_base_template, name="index-render-html-with-base-template"),
        path('index-render-html-with-block-content-using-base-template/', views.index_render_html_with_base_template, name="index-render-html-with-base-template"),
    

    Just put it after the last line of the URL address definition as into the following content :

    from django.contrib import admin
    from django.urls import path
    from . import views
    urlpatterns = [
        path('', views.index, name="index"),
        path('index-print-text/', views.index_print_text, name="index-print-text"),
        path('index-print-text-with-html-tags/', views.index_print_text_with_html_tags, name="index-print-text-with-html-tags"),
        path('index-render-plain-html/', views.index_render_plain_html, name="index-render-plain-html"),
        path('index-render-html-with-static-tags/', views.index_render_html_with_static_tags, name="index-render-html-with-static-tags"),
        path('index-render-html-with-base-template/', views.index_render_html_with_base_template, name="index-render-html-with-base-template"),
        path('index-render-html-with-block-content-using-base-template/', views.index_render_html_with_base_template, name="index-render-html-with-base-template"),
        path('index-render-html-with-value-from-context-parameter-and-block-content-using-base-template/', views.index_render_html_with_value_from_context_parameter_and_block_content_using_base_template, name="index-render-html-with-value-from-context-parameter-and-block-content-using-base-template"),
    
    
  2. Going through the next step, create a new function accordingly. In other words, create a function in the ‘views.py’ file with the function name of the one defined in the new URL address. Add it  in the ‘views.py’ file as in the one exist below :

    def index_render_html_with_value_from_context_parameter_and_block_of_base_template(request):
        context = {
            "title":"This is a title of Document",
            "message":"This is a string passed from the Django Application Backend Function"
        } 
        template_name = 'myapp/index-html-with-value-from-context-parameter-and-block-content-using-base-template.html'
        return render(request, template_name, context=context)

    In the function definition above, there is another additional variable. It is a dictionary variable containing two parameters. First parameter will be for the value of the title of the base HTML template file. Second parameter will be for the value of the block content which exist inside the HTML file. In the above case, there is a process for passing or delivering the variable is  according to the above function definition :

    return render(request, template_name, context=context)
  3. So, in order to process the above function,  there is a need to have an HTML file with the name of ‘index-html-with-value-from-context-parameter-and-block-content-using-base-template.html’. After creating the file, extends it from the base template since the HTML file is using it. Put it as the file will be exist in the following structure in the Django application templates folder as follows :

    C:\django\myproject>tree /A .
    Folder PATH listing for volume Windows-SSD
    Volume serial number is CA30-19A4
    C:\django\myproject
    +---myapp
    |   +---migrations
    |   | \---__pycache__
    |   +---static
    |   |   \---myapp
    |   |       +---css
    |   |       \---js
    |   +---templates
    |   |   \---myapp
    |   |       +--- base.html 
    |   |       \--- index-html-with-value-from-context-parameter-and-block-content-using-base-template.html 
    |   \---__pycache__
    \---myproject
        \---__pycache__
    
    C:\django\myproject>

    Before going on further with the HTML file, just make sure that there is a base HTML file with the name of ‘base.html’. Below is the existing content of the original ‘base.html’ file :

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h1>This content is from HTML Base Template File</h1>
        {% block content %}
        {% endblock %}
    </body>
    </html>

    It is very useful for proving that there is a possible feature for passing value to the base HTML template, just modify the ‘<title></title>’ tag by inserting a new parameter. Just adjust the new inserted parameter {{title}} in the ‘<title></title>’ tag as follows :

    <title>{{title}}</title>

    Perform the modification of the ‘base.html’ base HTML template, so the content of the ‘base.html’ will be exist as follows :

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>{{title}}</title>
    </head>
    <body>
        <h1>This content is from HTML Base Template File</h1>
        {% block content %}
        {% endblock %}
    </body>
    </html>
  4. Beside the ‘base.html’ file, also modify the HTML file where the block content exist. It will show the feature for passing value of the context variable. So for the next step is for creating the HTML which is going to use the base HTML. That file is the one with the name of ‘index-html-with-value-from-context-parameter-and-block-content-using-base-template.html’. Just modify the block content by inserting a new parameter in {% block content %} {% endblock %} as follows :

    {{ message }}

    So, the content of the HTML file will be as follows :

    {% extends 'myapp/base.html' %}
    {% block content %}
    <h1>This content is from HTML File under Block Content</h1>
    <h2>{{ message }} </h2>
    {% endblock %}
  5. Last but not least, just execute an internal server exist in the Django project. Right after that, try to access the URL ‘localhost:8000/myapp/index-html-with-value-from-context-parameter-and-block-content-using-base-template/’. After accessing that URL address, there will be a page appear as follows :

    How to Pass Value using Variable to HTML File in Django Application
    How to Pass Value using Variable to HTML File in Django Application

    In the page above as output, there is a another string which is not exist in the base template HTML file. It is a string which is available in the block content of the HTML file. In that case, the usage of a content block which is only specific for that HTML file is a success.

Leave a Reply