user2746203
user2746203

Reputation:

Django: Use a variable from a view in a template

I want to use the content of a variable with the name "files" in my template in django. My views.py looks like this:

from django.shortcuts import render

import os


def index(request):
        os.chdir("/home/ubuntu/newproject/static")
        for files in os.listdir("."):
                return render(request, 'sslcert/index.html','files')

And my template with the name "index.html" looks like this:

<head>
        {% block title %}
        <h3>
                        Following directories are in this folder:
        </h3>
        {% endblock %}
</head>



<body>
        <<(HERE SHOULD BE THE OUTCOME OF THE VARIABLE LIST)>>
</body>

Help would be really cool and explanation too :/ I am a real beginner in django and I wish to know how this template and views stuff is connected :) please do not hate on me if this question is really stupid :(

Upvotes: 0

Views: 4549

Answers (3)

TankorSmash
TankorSmash

Reputation: 12747

Do something like:

from django.shortcuts import render
import os

def index(request):
        os.chdir("/home/ubuntu/newproject/static")
        files = []
        for file in os.listdir("."):
            files.append(file)

        context = {'files':files}
        return render(request, 'sslcert/index.html', context)

and then the template:

<head>
        {% block title %}
        <h3>
              Following directories are in this folder:
        </h3>
        {% endblock %}
</head>

<body>
       {{ files }}
</body>

Upvotes: 2

iblazevic
iblazevic

Reputation: 2733

You can pass variable to template like this:

from django.shortcuts import render_to_response

def index(request):
    os.chdir("/home/ubuntu/newproject/static")
    for file in os.listdir("."):
        files.append(file)
    return render_to_response('sslcert/index.html', {'files':files})

And in template you can use it like:

{{files}}

if you want to use whole field or you can loop through them

{% for file in files %}
# do something with file here
{% endfor %}

Upvotes: 3

oleg
oleg

Reputation: 4182

render function You are using in Your example got dictionary argument which can extend context passed into template

render(request, template_name[, dictionary][, context_instance][, content_type][, status][, current_app][, dirs])

dictionary A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the view will call it just before rendering the template.

so you can pass any data into template as dictionary which keys will be available in template as variable

from django.shortcuts import render

def index(request):
    dir = "/home/ubuntu/newproject/static"
    return render('sslcert/index.html', {'files': os.listdir(dir)})

Upvotes: 0

Related Questions