Django Not Found: /media/ , GET /media/ HTTP/1.1" 404 2679


I am currently building a project which i have to use media. Since i have used media before i copy pasted everyting from my other project and altough the original is working my current project is not. I can upload and select fotos thru admin page but it does not show up in html

My view:

def index(request):

    dergi = Dergi.objects.all()
    kitap = Kitap.objects.all()
    yazar = Yazar.objects.all()
    siir = Siir.objects.all()

    template = loader.get_template("index.html")
    return HttpResponse(template.render(context, request))

My model:

class Kitap(models.Model):
    isim = models.CharField(max_length=255)
    yazar = models.CharField(max_length=255)
    foto = models.ImageField(upload_to="foto", null=True)

My url:

urlpatterns = [
path("", include("index.urls"))

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

And my html:

<img src="/media/{{ KITAP.foto }}" alt="" class="rounded-t-lg">
<img src="/media/{{ KITAP.foto.url }}" alt="" class="rounded-t-lg">
<img src="{{ KITAP.foto.url }}" alt="" class="rounded-t-lg">

i have tried all but it just gives me error:
GET /media/ HTTP/1.1" 404 2679 or:
Not Found: /foto/

Asked By: PlatinMavi



Since you are sending all the instances of Kitap model using .all() method, so you should iterate over all the instances, like so:

{% for ki in KITAP %}
    <img src="{{ ki.foto.url }}" alt="" class="rounded-t-lg">
{% endfor %}
Answered By: Sunderam Dubey

As per your index view function KITAP is a queryset not a single query. try for loop in template or send a single object from view using Kitap.objects.get(pk=some_value) method or something like KITAP[0] or get_object_or_404(id=some_value).

For loop in template will be like this:

{% for obj in KITAP %}
    <img src="{{ obj.foto.url }}" alt="" class="rounded-t-lg">
{% endfor %}
Answered By: Masud Dipu