0

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?

3
  • Rule of the thumb: any excessive logic should not be done in template but in the view. Anyway - accessing properties/values in templates is done via . operator, no matter what datastructure it is, so what you want is product_list.0 Commented Sep 1, 2021 at 22:08
  • Read about Variables in the Django documentation. If you want to access product_list[0] in the template you have to write it as {{ product_list.0 }}. Commented Sep 1, 2021 at 22:08
  • Is there an easier way to add multiple variables at once to a template? Commented Sep 1, 2021 at 22:35

1 Answer 1

3

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 %}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.