serving user upload files

Hi All,

I am trying to server the user uploads image. But in template post.image.url provides empty in browser end.

settings.py:

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = "django-insecure-@)9x@9-ve2u&u@@%#16yg+iwp-rbrd2z628+t8upj4yre&+t&@"

DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    "fileupload",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "fileuploaddemo.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "fileuploaddemo.wsgi.application"

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


STATIC_URL = "static/"


DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"


MEDIA_ROOT = os.path.join(BASE_DIR, "uploads/")
MEDIA_URL = "uploads/"

project level urls.py:


from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("fileupload.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

app level urls.py:


from django.urls import path
from .views import FileUpload, Files

urlpatterns = [
    path("", FileUpload.as_view(), name="home"),
    path("files", Files.as_view(), name="files"),
]

views:

from django.shortcuts import redirect, render
from django.views import View
from .form import UserUploads
from .models import File

# Create your views here.


class FileUpload(View):

    def get(self, request):
        return render(request, "home.html", {"form": UserUploads})

    def post(self, request):
        form = UserUploads(request.POST, request.FILES)

        if form.is_valid():
            form_data = form.cleaned_data
            image = form.cleaned_data["file"]
            File(title=form_data["title"], image_name=image).save()
            return redirect("files")
        else:
            return render(request, "home.html", {"form": form})


class Files(View):

    def get(self, request):

        data = File.objects.all().values()

        for i in data:
            print(i["title"])
            print(i["image_name"])

        return render(request, "file.html", {"posts": data})

models.py:


from django.db import models

class File(models.Model):
    title = models.CharField(max_length=100)
    image_name = models.FileField(upload_to="media/")

form.py:

from django import forms


class UserUploads(forms.Form):
    title = forms.CharField(max_length=100)
    file = forms.FileField()

template:

<!DOCTYPE html>

<html>
   
 {% for post  in posts %}

    <h2> {{ post.title }}</h2>

    <img src="{{ post.image_name.url }}" alt="{{ post.title }}" /> 

    {% endfor %}
</html>

I checked given Media root directory able to see file present there once uploaded via browser but when I try to server the image but not providing to browser.

Please review my code and tell me where I am doing mistake ?

thanks in advance

1 Like

In your browser if you View Source of the page, what is the URL in the img’s src attribute?

its coming as empty

image

its so confusing for me.

What is your debugging outputting in the logs, the print(i["image_name"])? Or, if you like at your File objects in Django Admin, do they have their image_name fields set?

my debugging output is below

I am able to see file objects in django admin and it have values

file also storing given location

Side Note: When posting code here, enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted. (I’ve taken the liberty of fixing your original post in this thread. Please remember to do this in the future.

There is an issue here:

Remove the .values() function. It’s not necessary, and is a cause of these symptoms.

You’re returning the values only for the File objects, not the file instances themselves. The image_name field has a url attribute associated with it, but the string value from the field does not.

@KenWhitesell as you suggestion I removed values() and executed my code. This time I got src but file not displaying.

Attached screenshot below

I’m sorry, I can’t read the image. Please copy/paste the rendered html into the body of your post.

Also please copy/paste the requests being shown for these images from your runserver console.

console log below

[11/Apr/2024 12:03:27] "GET /admin/ HTTP/1.1" 302 0
[11/Apr/2024 12:03:27] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 4158
[11/Apr/2024 12:03:29] "GET / HTTP/1.1" 200 1176
[11/Apr/2024 12:03:32] "GET / HTTP/1.1" 200 1176
[11/Apr/2024 12:03:33] "GET /files HTTP/1.1" 200 657
Not Found: /Users/manojkumar19/Desktop/Python Project/Django Learning/learning_projects/Project-5_file_uploads/fileuploaddemo/uploads/media/9fa6fdb0-b6bb-4443-a314-f46fe6129ef8.jpg
Not Found: /Users/manojkumar19/Desktop/Python Project/Django Learning/learning_projects/Project-5_file_uploads/fileuploaddemo/uploads/media/8910-min.JPG
Not Found: /Users/manojkumar19/Desktop/Python Project/Django Learning/learning_projects/Project-5_file_uploads/fileuploaddemo/uploads/media/8910.JPG
[11/Apr/2024 12:03:33] "GET /Users/manojkumar19/Desktop/Python%20Project/Django%20Learning/learning_projects/Project-5_file_uploads/fileuploaddemo/uploads/media/9fa6fdb0-b6bb-4443-a314-f46fe6129ef8.jpg HTTP/1.1" 404 3047
[11/Apr/2024 12:03:33] "GET /Users/manojkumar19/Desktop/Python%20Project/Django%20Learning/learning_projects/Project-5_file_uploads/fileuploaddemo/uploads/media/8910-min.JPG HTTP/1.1" 404 2963
[11/Apr/2024 12:03:33] "GET /Users/manojkumar19/Desktop/Python%20Project/Django%20Learning/learning_projects/Project-5_file_uploads/fileuploaddemo/uploads/media/8910.JPG HTTP/1.1" 404 2951
[11/Apr/2024 12:04:01] "GET /files HTTP/1.1" 200 657
Not Found: /Users/manojkumar19/Desktop/Python Project/Django Learning/learning_projects/Project-5_file_uploads/fileuploaddemo/uploads/media/8910-min.JPG
[11/Apr/2024 12:04:01] "GET /Users/manojkumar19/Desktop/Python%20Project/Django%20Learning/learning_projects/Project-5_file_uploads/fileuploaddemo/uploads/media/8910-min.JPG HTTP/1.1" 404 2963
Not Found: /Users/manojkumar19/Desktop/Python Project/Django Learning/learning_projects/Project-5_file_uploads/fileuploaddemo/uploads/media/8910.JPG
Not Found: /Users/manojkumar19/Desktop/Python Project/Django Learning/learning_projects/Project-5_file_uploads/fileuploaddemo/uploads/media/9fa6fdb0-b6bb-4443-a314-f46fe6129ef8.jpg
[11/Apr/2024 12:04:01] "GET /Users/manojkumar19/Desktop/Python%20Project/Django%20Learning/learning_projects/Project-5_file_uploads/fileuploaddemo/uploads/media/8910.JPG HTTP/1.1" 404 2951
[11/Apr/2024 12:04:01] "GET /Users/manojkumar19/Desktop/Python%20Project/Django%20Learning/learning_projects/Project-5_file_uploads/fileuploaddemo/uploads/media/9fa6fdb0-b6bb-4443-a314-f46fe6129ef8.jpg HTTP/1.1" 404 3047

Html Rendered in browser:

• <html> == $0
<head></head>
• <body>
<h2> test</h2>
<img src="/Users/manoj kumar19/Desktop/Python Project/Django Learning/learning_pects/Project-5 file uploads/fileuploaddemo/uploads/media/8910-min.JPG" alt="test">
<h2> test</h2>
<img src="/Users/manoj kumar19/Desktop/Python Project/Django Learning/learning_ projects/Project-5 file uploads/fileuploaddemo/uploads/media/8910.JPG" alt="test">
<h2> test</h2>
<img src="/Users/manojkumar19/Desktop/Python Project/Django Learning/learning_P../fileuploaddemo/uploads/media/9fa6fdb0-b6bb-4443-a314-f46fe6129ef8_jpg" alt="test">
</body>
</html>

browser console log:

& Failed to load resource: the server responded with a status of 404 (Not Found) 8910-min.JPG:1
& Failed to load resource: the server responded with a status of 404 (Not Found) 8910. JPG: 1
& Failed to load resource: the server responded with a status of 404 (Not Found) 9fafdb0-b6bb-4443-a…-f46fe6129ef8-jpg:1

I hope above logs is enough

Your MEDIA_URL should be an absolute path, not relative. (e.g. MEDIA_URL='/uploads/')

@KenWhitesell

is that correct ?


MEDIA_ROOT = os.path.join(BASE_DIR, "uploads/")
MEDIA_URL = "/uploads/"

I tried with same but same error Image not found

Not Found: /Users/manojkumar19/Desktop/Python Project/Django Learning/learning_projects/Project-5_file_uploads/fileuploaddemo/uploads/media/9fa6fdb0-b6bb-4443-a314-f46fe6129ef8.jpg
[11/Apr/2024 12:22:39] "GET /Users/manojkumar19/Desktop/Python%20Project/Django%20Learning/learning_projects/Project-5_file_uploads/fileuploaddemo/uploads/media/9fa6fdb0-b6bb-4443-a314-f46fe6129ef8.jpg HTTP/1.1" 404 3047

Again, you’ve got an issue here where you’re trying to work with the string path and not an image field.

Your form should be a model form that binds the upload data directly to the model fields. See the docs and examples at Handling uploaded files with a model.

@KenWhitesell thanks advice now image loading.