I am trying to display images that are upload by the user in my HTML. I'd set the following:
Settings:
MEDIA_URL = '/media/'
MEDIAFILES_DIRS = []
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
Upload files within the model to directory:
class Artikel(models.Model):
artikel_pic = models.ImageField(upload_to='assortiment/images/', blank=True, verbose_name="Afbeelding")
urls:
urlpatterns = [
path(r'', include('main.urls')),
path(r'', include('assortiment.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Views.py:
class AssortimentView(TemplateView):
template_name = "assortiment/assortiment.html"
def get(self, request):
artikel = Artikel.objects.all()
context_artikel = { 'artikel': artikel}
return render (request, self.template_name, context_artikel)
url that is given when i open the image in the admin panel: http://127.0.0.1:8000/media/assortiment/images/choco_ijs.jpg It displays correctly over here.
html code that needs to diplay the image:
{% for art in artikel %}
<div class="col-sm-2">
<div class="card" >
<img class="card-img-top" src="{{MEDIA_URL}}/images{{ artikel_pic.url }}" alt="{{art.artikel_naam}}">
<div class="card-body">
<h5>{{ art.artikel_naam }}</h5>
<p class="card-text">{{ art.artikel_omschrijving }}</p>
</div>
<div class="row mr-auto">
<div class="col-8">
<button type="submit" href="#" class="btn btn-info" id="button-assortiment-info">info </button>
</div>
<div class="col-4">
<button type="submit" href="#" class="btn btn-primary" id="button-assortiment-add">+</button>
</div>
</div>
</div>
</div>
{% endfor %}
I get a not found (304) error: "GET /media/assortiment/images/choco_ijs.jpg HTTP/1.1" 304
It looks like everything is going fine. Can't figure out what is going wrong though. I tried to change the src within the html file to:
<img class="card-img-top" src="{{ artikel_pic }}" alt="{{art.artikel_naam}}">
<img class="card-img-top" src="{{ artikel_pic.url }}" alt="{{art.artikel_naam}}">
<img class="card-img-top" src="/images/{{ artikel_pic.url }}" alt="{{art.artikel_naam}}">
<img class="card-img-top" src="{{MEDIA_URL}}{{ artikel_pic.url }}" alt="{{art.artikel_naam}}">
It seems like the source is not routing to the right one. Does anyone have some suggestions how to do this correctly?
add these lines in settings.py file
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media/')
and use this code in html file
<img class="card-img-top" src="{{ art.artikel_pic.url }}">