Django的多个图像不上传

时间:2018-08-13 05:01:37

标签: javascript python html django

因此,我一直在尝试使用JQuery作为客户端选择部件来一次上传多个文件的方法。我出于某种原因,它无法正常工作,我不确定为什么。

为要创建的项目添加图像时,页面没有任何反应。

我的代码如下:

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>"
          )
        }
      }
    });

  });

更新的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)

更新的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 个答案:

答案 0 :(得分:1)

您应将 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)