About Display uploaded files in Django Templates.

The question is simple, how do I display uploaded files on Django templates? I have a certain path for storing uploaded files which is written in MEDIA URL. now I want to display that pdf file or document on the Django template… If you read this then please provide solution ASAP…

Your question isn’t really django related. It’s more of a generic webdev/HTML question.

What you want to do is “embed” documents, which may be different depending on exactly what documents you want to embed.

Here’s a useful starter link: How to Embed PDF in HTML

Also, just for reference, “If you read this then please provide solution ASAP…” kind of sounds a little presumptious and demanding on a forum where people are helping on their own time.

I’m sorry, It seems like you didn’t understood my problem. I know about how to embed a document in HTML but Don’t know about how to display a document file on Django Template and I have already done with it but couldn’t get desired output. it shows server error 500 on the webpage of Django.

Then no, I don’t understand. You have the path to the file. You have your template. And you know how to embed a file.

I’m really not sure what you’re missing? If there are specific errors you’re going to have to show code and a stacktrace.

Let me explain my code,

display_files.html:

{% load static %}
{% for each in data %}




{% endfor %}

views.py:

def show_data(request):
if os.path.isfile(“D:\File Storage\File_Path.txt”):
f = open(“D:\File Storage\File_Path.txt”, ‘r’)
file_path = f.readlines()
arraydata =
for line in file_path:
array = line.split(“,”)
arraydata.append(array)
f.close()
data = FileUpload.objects.values_list(‘pdf_file’, flat=True)
return render(request, “display_files.html”, data)

I have implement both

You’ll need to expand on what you mean by “display a document file on Django Template” because that’s not very clear. Exactly what do you mean by “display”?

i don’t know but why html code couldn’t post in it, i have implemented both

You need to put three backticks ``` on separate lines before and after each block of code for it to be readable.

Okay, i can receive a document from user and store into folder ( in “D://” Drive ). the code of html and views.py as below still cannot open or display the document on html webpage of Django.

display_files.html:

<body>
    {% load static %}
    {% for each in data %}
      <div class="doc">
        <div class="file_desc">
          <iframe src="{{ each.url }}" width="100%" height="100%"></iframe>
          <a href="{{ each.url }}" width="100%" height="100%" > My files </a>
        </div>
      </div>
    {% endfor %}
  </body>

views.py:

from django.core.files.storage import FileSystemStorage
from django.shortcuts import render, HttpResponse
from .models import FileUpload
import os

# Avoid some extra imports
def show_data(request):
        if os.path.isfile("D:\\File Storage\\File_Path.txt"):  
            f = open("D:\\File Storage\\File_Path.txt", 'r')
            file_path = f.readlines()
            arraydata = []
            for line in file_path:
                    array = line.split(",")
                    arraydata.append(array)
            f.close()
            data = FileUpload.objects.values_list('pdf_file', flat=True)
        return render(request, "display_files.html", data)

No I was right when I deleted that comment…

data is a list, no? The template expects a dict with a “data” key where the corresponding value is iterable

I understand, Is there no other datatype that can be passed to the template?

And it means I should convert that data object into the Dictionary…right?

Your view appears to be doing two separate “things” that don’t have any relation to each other - and the first doesn’t appear to be doing anything for you.

All that work you’re doing for reading the “File_path.txt” file doesn’t accomplish anything. The only information you’re presenting to the user is what’s in your FileUpload model - and that is only gong to have data available if that file exists.

Where are you populating the FileUpload model?

Yes, this is my mistake, I assumed that files would be retrieved from File_path.txt .
FileUpload model is created in models.py. and is it right what I wrote in views.py except for the first logic which is related to File_path.txt…?

Show the code for your model.

models.py

from django.db import models

class FileUpload(models.Model):
    pdf_file = models.FileField()
    
    def __str__(self):
        return self.file_url.name

Thanks. As Ken said, you don’t need most of the code in your view because it’s not doing anything relevant and none of that data is being passed to your template.

Also, unless there’s a good reason, I wouldn’t use values_list() when getting your FileUpload objects. It’s not wrong, it’s just not useful here.

So you can get a list of your FileUpload objects and send it to the template like this:

def show_data(request):
    context = {
        "fileupload_list": FileUpload.objects..all(),
    }
    return render(request, "display_files.html", context)

Notes:

  1. The third argument to render() is a dict, conventionally called context. It’s introduced in the tutorial here.
  2. I’ve called the QuerySet of objects fileupload_list, which is what it will be available as in the template. You can choose anything, but consistency is good!

Then we can adjust your template like this:

<body>
    {% load static %}

    {% for fileupload in fileupload_list %}
      <div class="doc">
        <div class="file_desc">
          <iframe src="{{ fileupload.url }}" width="100%" height="100%"></iframe>
          <a href="{{ fileupload.url }}" width="100%" height="100%" > My file </a>
        </div>
      </div>
    {% endfor %}

</body>

BUT I don’t understand what you’re trying to do with these 100% wide and high iframes and as.

I have implementing both HTML and show_data function But after I implementing the provided code by you, no objects are returned from model. See when I print the context it returns {'fileupload_list': <QuerySet []>}. what is wrong with it…?

Sorry I had a typo in the above, it should be (one period removed):

    "fileupload_list": FileUpload.objects.all(),

It is not returning any error and I know it’s syntax, Even then it shows the same.

So you need to debug the problem.

In your view if you do print(FileUpload.objects.all()) what does it show in the logs?