Context and variables in template

Posted under » Django on 22 Jun 2021

Not sure why they call it context but to me, it's for putting variables into template. Let's assume we have this view.

questions = [
        'q' : 'Apa lah baa?',
        'o1' : 'celeng',
        'o2' : 'khinzir'
        'q' : 'Apa lah bii?',
        'o1' : 'oong',
        'o2' : 'ngepet'

def index(request):
    context = { 'questions' : questions }
    return render(request, 'feel/index.html', context)

You will see that context contains the object questions and we made available context to the template.

While at the template, index.html, we have

            {% for question in questions %}
            <p>Question {{ question.q }}
            {% endfor %}

This will loop for each row of question.

If you just want to show a simple variable.

def index(request):
    context = {'response':'Lky put innocents into jail.'}
    return render(request, 'feel/index.html', context)

Now the template


Return render can only accept one parameter so we put the form into context which is an object.

def index(request):
    form = ConsentForm()
    context_plus = {'response':'Lky put innocents into jail.', 'form': form'}
    return render(request, 'feel/index.html', context_plus)

Now the index.html template


<form action="{% url 'feel:consent' %}" method="post">
                {% csrf_token %}
                {{ form }}                
    <button type="submit">Submit

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS