Global variable doesn't work inside django views

Question:

I wanted to use some dummy data in my Django views to work with templates. When the posts variable is outside the home function all I’m getting is an empty body. Although when I move it inside everything displays as it should.

from django.shortcuts import render
posts = [
    {
        'author': 'Kamil', 
        'title' : 'Post 1',
        
    }, 
    {
        'author': 'Tomek', 
        'title' : 'Post 2',
    }, 
]

def home(request):
    context = {
        'posts' : posts
    }
    return render(request, 'blog_app/home.html', context)

Here is also my html

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>

    <body>
        {% for post in posts %}
            <h1>{{ post.title }}</h1>
            <p>By {{ post.author }}</p>
        {% endfor %}
    </body>
</html>
Asked By: Kamil Górny

||

Answers:

Make posts a global variable

global posts

posts = [
    {
        'author': 'Kamil', 
        'title' : 'Post 1',
        
    }, 
    {
        'author': 'Tomek', 
        'title' : 'Post 2',
    }, 
]
Answered By: danish_wani