Not displaying all the files I uploaded. Showing only one

I uploaded multiple files into my database. All file were uploaded and saved in database. But In front-end or even in django admin site. It is displaying only one file. I checked the database all the files what I have selected are uploaded but not showing all the files in front-end or django-admin site.

How to display all the files which are uploaded into my database in django?

We’ll need to see the models, forms, views, and ModelAdmin class for this.

Views.py

def create_course_save(request):
    if request.method == 'POST':
        courseCode = request.POST.get('course_code')
        courseName = request.POST.get('course_name')
        courseShortInfo = request.POST.get('course_short_info')
        courseWYWL = request.POST.get('course_wywl')
        courseSYWG = request.POST.get('course_sywg')
        courseDesc = request.POST.get('course_desc')
        courseCC = request.POST.get('course_coordinator')
        courseCC = User.objects.get(id=courseCC)
        courseBranch = request.POST.get('branch')
        courseSemester = request.POST.get('semester')
        courseSemester = Semester.objects.get(id=courseSemester)
        courseFiles = request.FILES.getlist('course_files')
        try:
            for file in courseFiles:
                courseObj = Course.objects.create(
                    course_code=courseCode,
                    course_name=courseName,
                    course_short_info=courseShortInfo,
                    course_wywl=courseWYWL,
                    course_sywg=courseSYWG,
                    course_desc=courseDesc,
                    course_coordinator=courseCC,
                    branch=courseBranch,
                    semester=courseSemester,
                    course_files=file)
        except Exception as e:
            print(e)
        return redirect('manage_courses')

models.py

class Course(models.Model):
    BRANCH_CHOICES = [
        ("","Branch Name"),
        ("Computer Science and Engineering","Computer Science and Engineering"),
        ("Aerospace/aeronautical Engineering","Aerospace/aeronautical Engineering"),
        ("Chemical Engineering","Chemical Engineering"),
        ("Civil Engineering","Civil Engineering"),
        ("Electronics and Communications Engineering","Electronics and Communications Engineering"),
        ("Electrical and Electronics Engineering","Electrical and Electronics Engineering"),
        ("Petroleum Engineering","Petroleum Engineering"),
        ("Bio Technology","Bio Technology"),
        ("Mechanical Engineering","Mechanical Engineering"),
    ]
    id = models.UUIDField(primary_key = True, unique = True, default = uuid.uuid4, editable = False)
    course_code = models.CharField(max_length = 100, unique = True)
    course_name = models.CharField(max_length = 100, unique = True)
    course_short_info = models.TextField(max_length = 500, default="Start your path to a career in project management. No degree or experience is required.")
    course_wywl = models.TextField(max_length = 500, default="WHAT YOU WILL LEARN")
    course_sywg = models.TextField(max_length = 500, default="SKILLS YOU WILL GAIN")
    course_desc = models.TextField(max_length = 500, default="Description of the Course")
    course_coordinator = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True)
    branch = models.CharField(max_length = 50, choices = BRANCH_CHOICES, default=1)
    semester = models.ForeignKey(Semester, on_delete=models.SET_NULL, blank=True, null=True)
    course_files = models.FileField(upload_to='Course Files/', blank=True, null=True)

    def __str__(self):
        return '%s - %s' % (self.course_code, self.course_name)

admin.py

from django.contrib import admin
from .models import (Course)

admin.site.register(Course)

Front-end (HTML)

    <label for="Upload Files">Upload Files</label>
    <input type="file" name="course_files" id="id_course_files" multiple>
    <input type="submit">

And I didn’t used forms

My requirement is to save the multiple files in one object. Is it possible? And What I observed is only one file is being saved in the databse for that object.

Each Field only stores a reference to one file.

Yes, an instance of a Model can store references to multiple files - if each file is assigned to a different Field.

And you really will save yourself a lot of work by using a form.

Could you share the code to it, Please or any reference to it. So, I can do it myself

Code to what? I don’t understand what you’re asking for.

Please did you later get this error fixed because I’m currently experiencing the same problem.

Please let me know how you fixed it

Hi Stanley, I’m not quite clear on your requirements. Could you please elaborate? Instead of mentioning errors, could you clarify what you need?

I keep on receiving this error “No file was submitted. Check the encoding type on the form”…even when I tried to create/Add from the Django admin. I didn’t create any html forms yet because I want to check from the backend first before creating any frontend form

I need to review the code for further debugging. Please share it here or on GitHub Repo.

Here are a few things to check:

views.py

from django.db import models

class MyModel(models.Model):
    my_file = models.FileField(upload_to='uploads/')

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

Just like this small project here. I uploaded multiple images but got only one image. I set validations in the views in other to know the cause and i got it out in the console with only one image and also with the form validation i set which states that form is Invalid

models.py

from django.db import models

class ImageUpload(models.Model):
  image = models.FileField(upload_to='images/')
  uploaded_at = models.DateTimeField(auto_now_add=True)

  def __str__(self):
    return f"Image uploaded at {self.uploaded_at}"

forms.py

from django import forms
from .models import ImageUpload

class ImageUploadForm(forms.ModelForm):

  image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': False})),

  class Meta:
    model = ImageUpload
    fields = ['image']
    

views.py

from django.shortcuts import render, redirect
from .forms import ImageUploadForm
from .models import ImageUpload

def upload_images(request):
  
  if request.method == 'POST':
    
    form = ImageUploadForm(request.POST, request.FILES)
    images = request.FILES.getlist('image')

    if form.is_valid():
      print('Valid Form')
    else:
      print('Form not Valid')
      
    for img in images:
      print(img)
      ImageUpload.objects.create(image=img)
      return redirect('upload_images')
   
  else:
    form = ImageUploadForm()
    
  images = ImageUpload.objects.all()
  return render(request, 'upload_images.html', {'form': form, 'images': images})

upload_images.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Upload Images</title>
</head>
<body>
  <h1>Upload Images</h1>
    
  <form action="" method="post" enctype="multipart/form-data">
      
    {% csrf_token %}

    {{form.as_p}}

    <button type="submit">Submit</button>

  </form>


  <h2>Uploaded Images</h2>
  
  <div>
    {% for image in images %}
      <img src="{{ image.image.url }}" alt="Image" style="max-width: 200px;"/>
    {% endfor %}
  </div>
</body>
</html>

My Console

[22/Sep/2024 16:09:28] "GET /media/images/agent-1.jpg HTTP/1.1" 304 0
Form not Valid-------(My form validation output which i set)
mini-testimonial-2.jpg-------(Instead of all images i got only one)
[22/Sep/2024 16:09:43] "POST /images/ HTTP/1.1" 302 0

Allow multiple file uploads by changing multiple: False to multiple: True.

image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

Move the redirect statement outside the loop to ensure all images are processed. Print out form errors for better debugging.

from django.shortcuts import render, redirect
from .forms import ImageUploadForm
from .models import ImageUpload

def upload_images(request):
    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        images = request.FILES.getlist('image')

        if form.is_valid():
            print('Valid Form')
            for img in images:
                print(img)
                ImageUpload.objects.create(image=img)
            return redirect('upload_images')  # Move this outside the loop
        else:
            print('Form not Valid')
            print(form.errors)  # Print form errors for debugging
            
    else:
        form = ImageUploadForm()

    images = ImageUpload.objects.all()
    return render(request, 'upload_images.html', {'form': form, 'images': images})