Django multiple images not uploading

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Django multiple images not uploading



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 %




1 Answer
1



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


POST


require_http_methods


get_create_form()


@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)





Its finally not outputting the method thing man! Thank you! The files still dont get uploaded tho :(
– Elly Richardson
Aug 13 at 5:11





@EllyRichardson you have to change your get_create_form() view to a meaningful one. Currently, it's do nothing
– JPG
Aug 13 at 5:14


get_create_form()





I thought that whenever I call get_create_form I will be sent to the forms.html, and then when I click "upload" the JQuery will process the images, and then the create_projects function will put it in the database if it is valid. What should I change?
– Elly Richardson
Aug 13 at 5:59






it won't work. you have to do validation and upload process in a single view
– JPG
Aug 13 at 6:02


validation


upload





Oh ok. So I updated my createprojects as a class. But it is still not doing anything. My JsonResponse says Data is not valid. I had it working before but had to change for a better code.
– Elly Richardson
Aug 13 at 6:12







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard