I’m new to Django and I’m now stuck at a problem of getting an image from a database displayed in an HTMl via it’s URL. I had a code that was already working and I now tried to add advanced features and that’s were all started to fall apart.
So first of all what’s already working:
I have a Database where I store the URLs of Images and other data. I then display the images and the other data in a “Report”-Template.
This is my view.py for this:
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from .utils import get_report_image
from .models import Report1
from django.views.generic import ListView, DetailView
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
import pandas as pd
class ReportListView(ListView):
model = Report1
template_name = 'reports/main.html'
class ReportDetailView(DetailView):
model = Report1
template_name = 'reports/detail.html'
# Create your views here.
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
def create_report_view(request):
if is_ajax(request):
report_id = request.POST.get('report_id')
name = request.POST.get('name')
remarks = request.POST.get('remarks')
img_Energie = request.POST.get('img_Energie')
img_Emissionen = request.POST.get('img_Emissionen')
img_Energie = get_report_image(img_Energie)
img_Emissionen = get_report_image(img_Emissionen)
#print("report_id: ", report_id)
Report1.objects.create(report_id = report_id, name=name, remarks=remarks, image_Energie=img_Energie, image_Emissionen=img_Emissionen)
return JsonResponse({'msg': 'send'})
return JsonResponse({})
and this is my template in html:
{% extends "base.html" %}
{% block title %}
{{ object.name }}
{% endblock title %}
{% block content %}
<h1>{{ object.name }}</h1>
<style>
table {text-align: left;}
table thead th {text-align: left;}
</style>
<!--{% if object.image_Energie %} -->
<img src="{{object.image_Energie.url}}" class="img-fluid" alt="{{object.name}}">
<img src="{{object.image_Emissionen.url}}" class="img-fluid" alt="{{object.name}}">
<!--{% else %}
no data
{% endif %} -->
<br>
<h4>Tabelle Berechnungen</h4>
<h5>Energie</h5>
<table class="table table-striped">
{{html_data_df_Energie|safe}}
</table>
<h5>Emissionen</h5>
<table class="table table-striped">
{{html_data_df_Emissionen|safe}}
</table>
<br>
<h3>Remarks</h3>
<p>{{object.remarks}}</p>
<hr>
<p>created: <b>{{object.created}}</b></p>
{% endblock content %}
these are my settings.py (part of):
STATIC_URL = 'static/'
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"
CRISPY_TEMPLATE_PACK = "bootstrap5"
STATICFILES_DIRS = [
BASE_DIR / 'static',
]
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
and these are my urlpatterns in the urls.py:
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
So again, that is working totally fine.
Now to what isn’t working:
In the views.py I wanted to include three models (the one I already had (Report1) and two other) due to a better data-management in the future. I used a super.get_context_data()-Function and I tried to read out the url of the Image after getting the entry in the Database over the self.get_object()-Function.
I checked weather the url of the image was right via the print-statement print("Report1_obj image_Energie url: ", Report1_obj.image_Energie)
and it was the correct one. I handed over the object to the template via the context-dictionary.
Now the issue occures: when I try to display the image over the Django-Template-Variable, as I did it in the previous version (see above) it’s not working anymore.
This is my view.py of the not-working version:
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from .utils import get_report_image
from .models import Report1
from datenverwaltung.models import Data_Entry_Energie, Data_Entry_Emissionen
from django.views.generic import ListView, DetailView
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
import pandas as pd
class ReportListView(ListView):
model = Report1
template_name = 'reports/main.html'
class ReportDetailView(DetailView):
model = Report1
template_name = 'reports/detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
Report1_obj = self.get_object()
print("Report1_obj image_Energie url: ", Report1_obj.image_Energie)
report_id = Report1_obj.report_id
print("ausgelesenen report_id: ", report_id)
Energie_Berechnungen_obj = Data_Entry_Energie.objects.filter(report_id=report_id)
Emissionen_Berechnungen_obj = Data_Entry_Emissionen.objects.filter(report_id=report_id)
context = {
'Report1_obj': Report1_obj,
'Energie_Berechnungen_obj': Energie_Berechnungen_obj,
'Emissionen_Berechnungen_obj': Emissionen_Berechnungen_obj
}
return context
# Create your views here.
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
def create_report_view(request):
if is_ajax(request):
report_id = request.POST.get('report_id')
name = request.POST.get('name')
remarks = request.POST.get('remarks')
img_Energie = request.POST.get('img_Energie')
img_Emissionen = request.POST.get('img_Emissionen')
img_Energie = get_report_image(img_Energie)
img_Emissionen = get_report_image(img_Emissionen)
#print("report_id: ", report_id)
Report1.objects.create(report_id = report_id, name=name, remarks=remarks, image_Energie=img_Energie, image_Emissionen=img_Emissionen)
return JsonResponse({'msg': 'send'})
return JsonResponse({})
def render_pdf_view(request, pk):
template_path = 'reports/pdf.html'
obj = get_object_or_404(Report1, pk=pk)
context = {'obj': obj}
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'filename="report.pdf"'
template = get_template(template_path)
html = template.render(context)
pisa_status = pisa.CreatePDF(html, dest=response)
if pisa_status.err:
return HttpResponse('We had some errors <pre>' + html + '</pre>')
return response
and this is my html-template:
{% extends "base.html" %}
{% block title %}
{{ Report1_obj.name }}
{% endblock title %}
{% block content %}
<h1>{{ Report1_obj.name }}</h1>
<style>
table {text-align: left;}
table thead th {text-align: left;}
</style>
<pre>{{ Report1_obj|safe }}</pre>
<!--{% if object.image_Energie %} -->
<!--{% if Report1_obj.image_Energie %} -->
<!-- <p>Energie Bild URL: <a href={{ Report1_obj.image_Energie }} target="_blank">{{ Report1_obj.image_Energie }}</a></p> -->
{{ Report1_obj.image_Energie.url }}
<img src="{{ Report1_obj.image_Energie.url }}" class="img-fluid" alt="{{ Report1_obj.name }}">
<!-- {% else %}-->
<p>Energie Bild nicht verfügbar.</p>
<!--{% endif %} -->
<img src="{{Report1_obj.image_Emissionen}}" class="img-fluid" alt="{{Report1_obj.name}}">
<!--{% else %}
no data
{% endif %} -->
<br>
<h4>Tabelle Berechnungen</h4>
<h5>Energie</h5>
<table class="table table-striped">
{{html_data_df_Energie|safe}}
</table>
<h5>Emissionen</h5>
<table class="table table-striped">
{{html_data_df_Emissionen|safe}}
</table>
<br>
<h3>Remarks</h3>
<p>{{Report1_obj.remarks}}</p>
<hr>
<p>created: <b>{{Report1_obj.created}}</b></p>
{% endblock content %}
What confuses me even more is that the <p>{{Report1_obj.remarks}}</p>
and <p>created: <b>{{Report1_obj.created}}</b></p>
are getting displayed. I didn’t change anything in the url-settings and others and the folder-structure is still the same.
I tried to change settings in the urls.py and in the settings.py but I can’t understand why the error occures. I was working on the problem for the last two days and also couldn’t find an answer in other posts, so I decided to post my question here.
As already said, I’m new to Dajango and happy for every hint.
Kind regards
rika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.