Search code examples
javascriptpythonhtmldjangovariables

How to (easily) put python variables from Django into html?


In one of my Django projects in views.py I've got some code:

from django.shortcuts import render
from django.http import HttpResponse
from .models import *

# Create your views here.

products = Product.objects.all()
product_list = list(products)

def displayhome(request):
    return render(request, 'bootstrap/index.html', {'title': product_list[0].title}, {'link': product_list[0].official_path_name})

Now using this (very clunky) method, I am able to put the string version of variables into html using:

{{title}}

for example. However this does not let me operate on the variables, e.g. if I sent through product_list I couldn't get product_list[0]. I vaguely know of using {% %} tags instead of {{ }} but I am (a) not completely sure how they work and (b) don't know how powerful they are e.g. if you could use it like a normal python file.

How would I use a variable from python (say it is an integer with value 4) to create a variable number of html elements (e.g. 4 boxes) for example?

If there is no easy way to execute python in html, is there a way to instead put my python variables into javascript and then somehow use those in the html instead?


Solution

  • I use this structure for my views:

    def your_view(request):
        myResult = MODEL_NAME.objects.all()
    
        context = {
                "variable1":[0,1,2,3,4,5,6],
                "variable2":"This is the variable 2",
                "variable3":"This is the variable 3",
                "variable4":myResult
                }
        return render(request, 'your_html.html', context)
    

    and you can access the variables in the template like this

    <!-- See variables by index   -->
    {{ variable1.0 }}
    {{ variable1.2 }}
    
    <!-- Iterate over variables -->
    {% for x in variable1 %}
          {{ x }}
    {% endfor %}
    
    <!-- Variable 2 & 3 -->
    {{ variable2 }}
    {{ variable3 }}
    
    <!-- Query set result -->
    {% for x in variable4 %}
          {{ x.id }}
          {{ x.name }} <!-- and all the other values from your model -->
    {% endfor %}