我一直在尝试实现一种使用JQuery上传多个图像的方法。由于某些原因,当我单击“上传照片”按钮时,我的js文件没有被调用。
每当我单击“上传照片”按钮时,都不会发生任何事情。
更新:我认为我的js文件未加载,并且出现了浏览器控制台中显示的问题
我的代码如下:
我不确定视图中的create_posts函数是否做错了什么。。
views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.utils import timezone
from django.core.files.base import ContentFile
from django.forms import modelformset_factory
from django.http import JsonResponse
from .models import Projects, P_Images
from .forms import ProjectsForm, P_ImageForm
from PIL import Image
from io import BytesIO
# Create your views here.
# Function to create projects
def create_projects(request):
#P_ImageFormSet = modelformset_factory(P_Images,form=P_ImageForm, extra=3)
# Special case if the request method is not POST
#if request.method == 'POST':
project_form = ProjectsForm(request.POST, request.FILES)
p_photos = 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()
p_photos.save()
data = {'is_valid': True, 'name': p_photos.file.name, 'url': p_photos.file.url}
else:
data = {'is_valid': False}
# print(project_form.errors, p_formset.errors)
#return JsonResponse(data)
context = {
'project_form': project_form,
'p_photos': p_photos,
}
return render(request, 'projects/test2.html', context)
# 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)
urls.py
from django.urls import re_path, include
from . import views
# urls for projects page
app_name = 'p_photos'
urlpatterns = [
re_path(r'^$', views.retrieve_projects, name="retrieve_projects"),
re_path(r'^create/$', views.create_projects, 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"),
]
在加载静态文件方面,我的html做错了吗?
test2.html
{% extends "projects/test.html" %}
{% block javascript %}
{% 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="file" multiple
style="display: none;"
data-url="{% url 'p_photos: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_photos %}
<tr>
<td><a href="{{ p_photo.file.url }}">{{ p_photo.file.name }}</a></td>
</tr>
{% endfor %}
</tbody>
</table>
<h1>hahahaha</h1>
{% endblock %}
test.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}Photos Library - Simple is Better Than Complex{% endblock %}</title>
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
</head>
<body>
<div class="container">
{% block content %}
{% endblock %}
</div>
<script src="{% static 'js/jquery-3.1.1.min.js' %}"></script>
<script src="{% static 'js/bootstrap/bootstrap.min.js' %}"></script>
{% block javascript %}
{% endblock %}
</body>
</html>
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>"
)
}
}
});
});
这是我的静态设置在我的settings.py中的样子
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, '..', 'static'),
)
浏览器控制台错误
Loading failed for the <script> with source “http://localhost:8000/static/js/jquery-3.1.1.min.js”. create:20
Loading failed for the <script> with source “http://localhost:8000/static/js/bootstrap/bootstrap.min.js”. create:21
[Show/hide message details.] ReferenceError: jQuery is not defined jquery.ui.widget.js:18:5
[Show/hide message details.] TypeError: $ is undefined jquery.iframe-transport.js:49:5
[Show/hide message details.] TypeError: $ is undefined jquery.fileupload.js:38:5
[Show/hide message details.] ReferenceError: $ is not defined basic-upload.js:1:1
答案 0 :(得分:0)
删除STATIC_ROOT,仅在收集静态文件时才应使用。还要确保您的JavaScript位于名为static
的文件夹中STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')