Django multiple images not uploading

Elly Richardson

So I have been trying to implement a way to upload multiple files at once using JQuery for the client-side choosing part. I For some reason it is not working and I am not sure why.

Nothing happens to my page whenever I add images for the project I want to create.

My code for this is below:

basic-upload.js

$(function () {
    /* 1. OPEN THE FILE EXPLORER WINDOW */
    $(".js-upload-photos").click(function () {
      $("#fileupload").click();
    });

    /* 2. INITIALIZE THE FILE UPLOAD COMPONENT */
    $("#fileupload").fileupload({
      dataType: 'json',
      done: function (e, data) {  /* 3. PROCESS THE RESPONSE FROM THE SERVER */
        if (data.result.is_valid) {
          $("#gallery tbody").prepend(
            "<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>"
          )
        }
      }
    });

  });

Updated views.py

class CreateProjectsView(View):
def get(self, request):
    p_photos = P_Images.objects.all()
    project_form = ProjectsForm(request.GET, request.FILES)
    context = {
        'p_photos': p_photos,
        'project_form': project_form,
    }
    return render(self.request, 'projects/forms.html', context)

def post(self, request):
    project_form = ProjectsForm(request.POST, request.FILES)
    p_formset = P_ImageForm(request.POST, request.FILES)

# Checks if the form is valid before save
if project_form.is_valid() and p_formset.is_valid():
    instance = project_form.save(commit=False)
    instance.user = request.user
    instance.save()
    images = p_formset.save(commit=False)
    images.save()

    data = {
        'is_valid': True, 
        'name': images.p_file.name, 
        'url': images.p_file.url
    }

else:
    data = {
        'is_valid': False,
    }

return JsonResponse(data)


# Function to retrieve all different projects
def retrieve_projects(request):
    # Retrieves objects based on latest publish date
    projects_list = Projects.objects.all().order_by("-publish_date")
    context = {
        'projects_list': projects_list,
    }
    return render(request, 'projects/projects.html', context)

# Function to update projects
def update_projects(request, slug):
    instance = get_object_or_404(Projects, slug=slug)
    project_form = ProjectsForm(request.POST or None, instance=instance)

    # Update_date becomes the latest time
    if project_form.is_valid():
        project_form.save()
        return redirect('retrieve_projects')
    context = {
        'instance': instance,
        'project_form': project_form
    }
    return render(request, 'projects/forms.html', context)

# Function to delete projects chosen
def delete_projects(request, slug):
    Projects.objects.filter(slug=slug).delete()
    return redirect('retrieve_projects')

# Function to show details of project using the ids
def details_of_project(request, slug):
    # Will raise 404 if there is not such id
    project_details = get_object_or_404(Projects, slug=slug)
    context = {
        'project_details': project_details,
    }
    return render(request, 'projects/posts.html', context)

forms.py

from django import forms

from .models import Projects, P_Images

class ProjectsForm(forms.ModelForm):

    class Meta:
        model = Projects
        #file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
        fields = ('images','title', 'description',)


class P_ImageForm(forms.ModelForm):
    #p_image = forms.ImageField(label='Image')  
    class Meta:
        model = P_Images
        fields = ('p_file',)

models.py

from django.db import models
from django.utils import timezone
from django.forms import ModelForm
from django.utils.text import slugify
from django.utils.crypto import get_random_string
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)
from PIL import Image

import os

DEFAULT_IMAGE_ID = 1

# Create your models here.
class Projects(models.Model):
    title = models.CharField(max_length=30)
    description = models.TextField(max_length=150)
    publish_date = models.DateTimeField(auto_now=False, auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True, auto_now_add=False)
    slug = models.SlugField(unique=True)
    files = models.FileField(upload_to='files/', blank=True)
    images = models.ImageField(upload_to='images/', height_field = 'img_height', width_field = 'img_width',blank=True)
    img_height = models.PositiveIntegerField(default=600)
    img_width = models.PositiveIntegerField(default=300)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        # Generates a random string 
        unique_string = get_random_string(length=32)

        # Combines title and unique string to slugify
        slugtext = self.title + "-" + "unique_id=-" + unique_string
        self.slug = slugify(slugtext)

        return super(Projects, self).save(*args, **kwargs)

def get_p_image_filename(instance, filename):
    title = instance.p_post.title
    slug_title = slugify(title)
    return "post_images/%s-%s" % (slug_slug, filename)

class P_Images(models.Model):
    p_file = models.ImageField(upload_to='images/', blank=None)
    p_uploaded_at = models.DateTimeField(auto_now_add=True, auto_now=False)
    #p_post = models.ForeignKey(Projects, on_delete=models.CASCADE, default=DEFAULT_IMAGE_ID)

Updated urls.py

from django.urls import re_path, include
from . import views

# urls for projects page
app_name = 'create_post'

urlpatterns = [
    re_path(r'^$', views.retrieve_projects, name="retrieve_projects"),
    re_path(r'^create/$', views.CreateProjectsView.as_view(), name="create_projects"),
    re_path(r'^(?P<slug>[\w-]+)/$', views.details_of_project, name="details_of_project"),
    re_path(r'^(?P<slug>[\w-]+)/update/$', views.update_projects, name="update_projects"),
    re_path(r'^(?P<slug>[\w-]+)/delete/$', views.delete_projects, name="delete_projects"),
]
    ]

forms.html

{% extends "projects/test.html" %}

{% block javascript %}

<form action="{% url 'create_post:retrieve_projects' %}" method="POST" enctype="multipart/form-data">

    {% csrf_token %}  

    {% for hidden in project_form.hidden_fields %}
    {{ hidden }}
    {% endfor %}

    {% for field in project_form %}
    {{ field }} <br />
    {% endfor %}

    <input type="submit" value="OK">

{% load static %}

{# JQUERY FILE UPLOAD SCRIPTS #}
<script src="{% static 'projects/js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script>
<script src="{% static 'projects/js/jquery-file-upload/jquery.iframe-transport.js' %}"></script>
<script src="{% static 'projects/js/jquery-file-upload/jquery.fileupload.js' %}"></script>

{# PHOTOS PAGE SCRIPTS #}
<script src="{% static 'projects/js/basic-upload.js' %}"></script>

{# 1. BUTTON TO TRIGGER THE ACTION #}
<button type="button" class="btn btn-primary js-upload-photos">
  <span class="glyphicon glyphicon-cloud-upload"></span> Upload photos
</button>

{# 2. FILE INPUT TO BE USED BY THE PLUG-IN #}
<input id="fileupload" type="file" name="p_file" multiple
       style="display: none;"
       data-url="{% url 'create_post:create_projects' %}"
       data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>

{# 3. TABLE TO DISPLAY THE UPLOADED PHOTOS #}
<table id="gallery" class="table table-bordered">
  <thead>
    <tr>
      <th>Photo</th>
    </tr>
  </thead>
  <tbody>
    {% for p_photo in p_formset %}
      <tr>
        <td><a href="{{ p_photo.file.url }}">{{ p_photo.file.name }}</a></td>
      </tr>
    {% endfor %}
  </tbody>
</table>

    <h1>hahahaha</h1>

</form>

{% endblock %}
JPG

You should add POST method to require_http_methods decorators of get_create_form() view as,

@require_http_methods(["GET","POST"])
def get_create_form(request):
    context = { 
        'project_form': ProjectsForm(),
        'p_formset': P_ImageForm(),
    }

    return render(request, 'projects/forms.html', context)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Uploading multiple images with Django

From Dev

Django REST: Uploading and serializing multiple images

From Dev

Uploading multiple images with volley?

From Dev

Uploading multiple images in codeigniter?

From Dev

Uploading multiple images with paperclip?

From Dev

Uploading multiple images in codeigniter?

From Dev

DRF: Uploading images in Django

From Dev

Uploading Multiple Images using CarrierWave

From Dev

Multiple images rename & uploading in PHP

From Dev

Multiple images rename & uploading in PHP

From Dev

Django-Filebrowser and uploading images

From Dev

All images not uploading in multiple images upload

From Dev

Uploading multiple images from Share Extension

From Dev

Uploading multiple images with other parameters in Swift

From Dev

Uploading multiple images to mysql database on Apache server

From Dev

PHP: Uploading multiple images to imgur at once

From Dev

multiple images uploading and converting them to thumbnails in cakephp

From Dev

PHP: Uploading multiple images at the same time

From Dev

Uploading multiple images in webservice using PHP

From Dev

Uploading multiple images using SRWebClient in Swift

From Dev

uploading/downloading multiple images the right way?

From Dev

Rails and carrierwave uploading multiple images fails

From Dev

filereader result order changing while uploading multiple images in javascript

From Dev

Issue uploading multiple images to a page with "upload" button...

From Dev

Uploading multiple images one to each row PHP and Mysqli db

From Dev

Jquery : Post Request is breaking while uploading multiple images

From Dev

Uploading multiple images on twitter using Ruby on Rails Twitter Gem

From Dev

Rails, uploading multiple images with carrierwave, but json not supported by my database

From Dev

only one record is saving when uploading multiple images in yii

Related Related

  1. 1

    Uploading multiple images with Django

  2. 2

    Django REST: Uploading and serializing multiple images

  3. 3

    Uploading multiple images with volley?

  4. 4

    Uploading multiple images in codeigniter?

  5. 5

    Uploading multiple images with paperclip?

  6. 6

    Uploading multiple images in codeigniter?

  7. 7

    DRF: Uploading images in Django

  8. 8

    Uploading Multiple Images using CarrierWave

  9. 9

    Multiple images rename & uploading in PHP

  10. 10

    Multiple images rename & uploading in PHP

  11. 11

    Django-Filebrowser and uploading images

  12. 12

    All images not uploading in multiple images upload

  13. 13

    Uploading multiple images from Share Extension

  14. 14

    Uploading multiple images with other parameters in Swift

  15. 15

    Uploading multiple images to mysql database on Apache server

  16. 16

    PHP: Uploading multiple images to imgur at once

  17. 17

    multiple images uploading and converting them to thumbnails in cakephp

  18. 18

    PHP: Uploading multiple images at the same time

  19. 19

    Uploading multiple images in webservice using PHP

  20. 20

    Uploading multiple images using SRWebClient in Swift

  21. 21

    uploading/downloading multiple images the right way?

  22. 22

    Rails and carrierwave uploading multiple images fails

  23. 23

    filereader result order changing while uploading multiple images in javascript

  24. 24

    Issue uploading multiple images to a page with "upload" button...

  25. 25

    Uploading multiple images one to each row PHP and Mysqli db

  26. 26

    Jquery : Post Request is breaking while uploading multiple images

  27. 27

    Uploading multiple images on twitter using Ruby on Rails Twitter Gem

  28. 28

    Rails, uploading multiple images with carrierwave, but json not supported by my database

  29. 29

    only one record is saving when uploading multiple images in yii

HotTag

Archive