[Answer]-Read a file in django and find string in file

1👍

Your problem is you are trying to use Python code in the template, like your open() call.

Django templates don’t work like that – you can only use a very limited set of syntax, and the syntax is not the same as Python.

Everything inside {{ }} and {% %} needs to be special Django template syntax, not Python code.

See the Django Template language documentation for the full details.

0👍

You can’t use code like this in a template directly see the documentation for available template tags and filters. From what I can tell by the code you have posted in your view.py you’ll need something like this:

docs=[]
for document in documents:
    if 'TheString' in open('/path/to/document').read():
        docs.append(document)

after passing docs to the template you could do this in the template:

{% for doc in docs %}
    <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li>
{% empty %}
    <p>No documents available.</p>
{% endfor %}

I’d need to look at what you are passing from the view to be sure of this, but I’d gladly assist in further help with further information if this doesn’t help.

Leave a comment