Swallow
Swallow

Reputation: 69

How to insert the content of text file in django template?

Django 1.7. I need to insert the content of text file from the model in django template. It's important that it must be a file not a text field of the model. Is there a way to do it? Here is my model:

class Model1(models.Model):
   file1 = FilerFileField(null=True, blank=True)
   file2 = FilerFileField(null=True, blank=True)

I tried {% include %} tag and it doesn't work.

Upvotes: 0

Views: 4199

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

{% include %} is for including templates (which will be searched in settings.TEMPLATE_DIRS) so no surprise it doesn't work.

Mainly, you'll have to read the files from Python code and pass it to the template's context. Three possible solutions here:

1/ add a method to your model to get your FilerFileField's content

2/ write a custom template filter (or tag) that takes the FilerFileField and returns the file's content

3/ read the FilerFileField's contents in the view and add them to the context

Upvotes: 2

Dmitry Astrikov
Dmitry Astrikov

Reputation: 657

Tag include is not about inserting something from model into your template. Is about inserting content of specified template. You need to write custom template filter which will read your file content and return it into template:

from django import template

register = template.Library()

@register.filter
def print_file_content(f):
    try:
        return f.read()
    except IOError:
        return ''

And use it into template like:

<div>{{ object.file1|print_file_content }}</div>

Or you can pass it through template context. Then just read file content into your view and add this content to your template context dictionary.

Upvotes: 1

Related Questions