How to use a function to print S3 data to HTML using Django?
Problem:
I had a correct connection to S3, because I am able to upload a PDF file to Amazon S3, but I can't display the S3 data into a Django template.
My expected result is when I open the page to view a PDF that I uploaded to Amazon S3, it should show all the PDFs that I have uploaded. But right now nothing is shown in the Django template.
Following is my code:
models.py
class PDFDocument(models.Model): title = models.CharField(max_length=100) pdf_file = models.FileField(upload_to='pdfs/') |
urls.py
path('display-pdf/<str:file_key>/', views.DisplayPDFView, name='display_pdf'), |
view.py
class DisplayPDFView(View): def get(self, request, file_key, *args, **kwargs): print(s3) s3 = boto3.client('s3') bucket_name = settings.AWS_STORAGE_BUCKET_NAME try: print('ds') response = s3.get_object(Bucket=bucket_name, Key=file_key) pdf_content = response['Body'].read() print(response) # Set the appropriate content type for PDF response = HttpResponse(pdf_content, content_type='application/pdf') response['Content-Disposition'] = f'inline; filename="{file_key}"'
return response
except s3.exceptions.NoSuchKey: return HttpResponse('PDF not found.', status=404) except: print("error")
|
viewCVpage.html
{% for pdf_document in pdf_documents %} <div class="col-md-4 col-sm-12"> <div class="card" style="width: 100%; float: left; margin-bottom: 10px;"> <!-- Display the PDF using an object tag --> <object data="{{ pdf_document.pdf_file.url }}" type="application/pdf" style="width: 100%; height: 400px;"> <p>Unable to display PDF. Please <a href="{{ pdf_document.pdf_file.url }}">download the PDF</a> instead.</p> </object> </div> </div> {% endfor %}
|
Solution 1:
Amazon S3 can be quite complex when it comes down to permission;
I had a correct connection to S3, because I am able to upload a PDF file to Amazon S3 |
The fact that you can upload, doesn't mean that you are able to read, and vice versa.
The first thing that I would suggest is to check whether you are able to list items from the specific S3 bucket. And if so, check what the output is.
Great, looking at how you set up the s3 client, it looks like there is something missing. You might need to add your aws_access_key_id && aws_secret_access_key. Something like this:
s3 = boto3.client( "s3", aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, ) |
Suggested blogs:
>How you can Show or hide elements in React?
>Login to Laravel API- Laravel
>Implement nested serializers in the Django rest framework
>Define blade component property in server - Laravel
>Sending Audio file from Django to Vue
>How to keep all query parameters intact when changing page in Django?
>Solved: TaskList View in Django
>Implement nested serializers in the Django rest framework