Dropzone upload works but needs styling

This commit is contained in:
HugoNeveux 2020-04-24 15:32:22 +02:00
parent 7838804ad0
commit 27c520554f
21 changed files with 354 additions and 9 deletions

View File

@ -126,6 +126,9 @@ USE_TZ = True
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/'),
)
# Logout redirect url
@ -134,3 +137,7 @@ LOGOUT_REDIRECT_URL = reverse_lazy('store_front_page')
# Login redirect url
LOGIN_REDIRECT_URL = reverse_lazy('store_front_page')
# Media_root
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

Binary file not shown.

View File

@ -50,12 +50,6 @@
</main>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="/docs/4.3/assets/js/vendor/jquery-slim.min.js"><\/script>')
</script>
<script src="/docs/4.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o"
crossorigin="anonymous"></script>
{% endblock %}

7
PDMI/static/dropzone-5.7.0/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
build
components
node_modules
.DS_Store
.sass-cache
_site
_config.yaml

View File

@ -0,0 +1,52 @@
{
"files": [
{
"name": "src/dropzone.coffee",
"regexs": [
"Dropzone.version = \"###\""
]
},
{
"name": "dist/dropzone.js",
"regexs": [
"version = \"###\""
]
},
{
"name": "dist/min/dropzone.min.js",
"regexs": [
"version=\"###\""
]
},
{
"name": "dist/dropzone-amd-module.js",
"regexs": [
"version = \"###\""
]
},
{
"name": "dist/min/dropzone-amd-module.min.js",
"regexs": [
"version=\"###\""
]
},
{
"name": "package.json",
"regexs": [
"\"version\": \"###\""
]
},
{
"name": "component.json",
"regexs": [
"\"version\": \"###\""
]
},
{
"name": "bower.json",
"regexs": [
"\"version\": \"###\""
]
}
]
}

View File

@ -0,0 +1,6 @@
Contribute
==========
DO NOT CREATE PULL REQUESTS ON GITHUB!
I will simply close them. If you want to contribute, please use [gitlab.com](https://gitlab.com/meno/dropzone) instead.

View File

@ -0,0 +1,12 @@
License
(The MIT License)
Copyright (c) 2012 Matias Meno <m@tias.me>
Logo & Website Design (c) 2015 "1910" www.weare1910.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,36 @@
<img alt="Dropzone.js" src="http://www.dropzonejs.com/images/new-logo.svg" />
Dropzone.js is a light weight JavaScript library that turns an HTML element into a dropzone.
This means that a user can drag and drop a file onto it, and the file gets uploaded to the server via AJAX.
* * *
_If you want support, please use [stackoverflow](http://stackoverflow.com/) with the `dropzone.js` tag and not the
GitHub issues tracker. Only post an issue here if you think you discovered a bug or have a feature request._
* * *
**Please read the [contributing guidelines](CONTRIBUTING.md) before you start working on Dropzone!**
<br>
<div align="center">
<a href="https://gitlab.com/meno/dropzone/builds/artifacts/master/download?job=release"><strong>&gt;&gt; Download &lt;&lt;</strong></a>
</div>
<br>
<br>
This is no longer the official repository for Dropzone. I have switched to [gitlab.com](https://gitlab.com/meno/dropzone)
as the primary location to continue development.
There are multiple reasons why I am switching from GitHub to GitLab, but a few of the reasons are the
issue tracker that GitHub is providing, *drowning* me in issues that I am unable to categorise or prioritize properly,
the lack of proper continuous integration, and build files. I don't want the compiled `.js` files in my repository, and
people regularly commit changes to the compiled files and create pull requests with them.
I will write a blog post soon, that goes into detail about why I am doing the switch.
This repository will still remain, and always host the most up to date versions of dropzone, but only the distribution
files!
MIT License
-----------

View File

@ -0,0 +1,16 @@
{
"name": "dropzone",
"location": "enyo/dropzone",
"version": "5.7.0",
"description": "Dropzone is an easy to use drag'n'drop library. It supports image previews and shows nice progress bars.",
"homepage": "http://www.dropzonejs.com",
"main": [
"dist/min/dropzone.min.css",
"dist/min/dropzone.min.js"
],
"ignore": [
"*",
"!dist",
"!dist/**/*"
]
}

View File

@ -0,0 +1,10 @@
{
"name": "dropzone",
"repo": "enyo/dropzone",
"version": "5.7.0",
"description": "Handles drag and drop of files for you.",
"scripts": [ "index.js", "dist/dropzone.js" ],
"styles": [ "dist/basic.css" ],
"dependencies": { },
"license": "MIT"
}

View File

@ -0,0 +1,18 @@
{
"name": "enyo/dropzone",
"description": "Handles drag and drop of files for you.",
"homepage": "http://www.dropzonejs.com",
"keywords": [
"dragndrop",
"drag and drop",
"file upload",
"upload"
],
"authors": [{
"name": "Matias Meno",
"email": "m@tias.me",
"homepage": "http://www.matiasmeno.com"
}],
"license": "MIT",
"minimum-stability": "dev"
}

View File

@ -0,0 +1 @@
module.exports = require("./dist/dropzone.js"); // Exposing dropzone

View File

@ -0,0 +1,40 @@
{
"name": "dropzone",
"version": "5.7.0",
"description": "Handles drag and drop of files for you.",
"keywords": [
"dragndrop",
"drag and drop",
"file upload",
"upload"
],
"homepage": "http://www.dropzonejs.com",
"main": "./dist/dropzone.js",
"maintainers": [
{
"name": "Matias Meno",
"email": "m@tias.me",
"web": "http://www.colorglare.com"
}
],
"contributors": [
{
"name": "Matias Meno",
"email": "m@tias.me",
"web": "http://www.colorglare.com"
}
],
"scripts": {
"test": "grunt && npm run test-prebuilt",
"test-prebuilt": "mocha-headless-chrome -f test/test-prebuilt.html -a no-sandbox -a disable-setuid-sandbox"
},
"bugs": {
"email": "m@tias.me",
"url": "https://gitlab.com/meno/dropzone/issues"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "https://gitlab.com/meno/dropzone.git"
}
}

View File

@ -1,6 +1,8 @@
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from bootstrap_modal_forms.mixins import PopRequestMixin, CreateUpdateAjaxMixin
from django import forms
from .models import Module
class CustomUserCreationForm(PopRequestMixin, CreateUpdateAjaxMixin,
UserCreationForm):
@ -12,3 +14,6 @@ class CustomAuthenticationForm(AuthenticationForm):
class Meta:
model = User
fields = ['username', 'password']
class FileFieldForm(forms.Form):
file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

View File

@ -1,3 +1,6 @@
from django.db import models
# Create your models here.
class Module(models.Model):
file = models.FileField()
name = models.CharField(max_length=255)
desc = models.TextField(max_length=2048)

32
PDMI/store/response.py Normal file
View File

@ -0,0 +1,32 @@
# encoding: utf-8
from django.http import HttpResponse
import json
MIMEANY = '*/*'
MIMEJSON = 'application/json'
MIMETEXT = 'text/plain'
def response_mimetype(request):
"""response_mimetype -- Return a proper response mimetype, accordingly to
what the client accepts, as available in the `HTTP_ACCEPT` header.
request -- a HttpRequest instance.
"""
can_json = MIMEJSON in request.META['HTTP_ACCEPT']
can_json |= MIMEANY in request.META['HTTP_ACCEPT']
return MIMEJSON if can_json else MIMETEXT
class JsonResponse(HttpResponse):
"""JSONResponse -- Extends HTTPResponse to handle JSON format response.
This response can be used in any view that should return a json stream of
data.
Usage:
def a_iew(request):
content = {'key': 'value'}
return JSONResponse(content, mimetype=response_mimetype(request))
"""
def __init__(self, obj='', json_opts=None, mimetype=MIMEJSON, *args, **kwargs):
json_opts = json_opts if isinstance(json_opts, dict) else {}
content = json.dumps(obj, **json_opts)
super(JsonResponse, self).__init__(content, mimetype, *args, **kwargs)

View File

@ -8,7 +8,6 @@
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">Profile</a>
<a class="dropdown-item" href="#">Settings</a>
<a class="dropdown-item" href="#">Upload module</a>
<a class="dropdown-item" href="{% url 'logout' %}">Logout</a>
</div>

View File

@ -0,0 +1,83 @@
{% extends "base/base.html" %}
{% load static %}
{% block extra_static %}
<script type="text/javascript" src="{% static 'dropzone-5.7.0/dist/dropzone.js' %}"></script>
<link rel="stylesheet" href="{% static 'dropzone-5.7.0/dist/dropzone.css' %}">
{% endblock extra_static %}
{% block body %}
<form class="dropzone clsbox" enctype="multipart/form-data" method="post" id="multiFileUpload">
<div class="fallback">
<input type="file" name="file" id="file" multiple />
<input type="submit" value="Upload" />
</div>
</form>
<script type="text/javascript">
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie != '') {
let cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = $.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
let csrftoken = getCookie('csrftoken');
Dropzone.autoDiscover = false;
$('#multiFileUpload').dropzone({
url: "{% url 'upload' %}",
crossDomain: false,
paramName: "file",
parallelUploads: 5,
autoProcessQueue: true,
filesizeBase: 1024,
maxFilesize: 10000,
dictRemoveFileConfirmation: null,
init: function() {
this.on('uploadprogress', function(file, progress, bytesSent) {
progress = bytesSent / file.size * 100;
console.log(filesizecalculation(bytesSent));
});
this.on("maxfilesexceeded", function(data) {
let res = eval('(' + data.xhr.responseText + ')');
});
this.on("addedfile", function(file) {
let removeButton = Dropzone.createElement("<button data-dz-remove " +
"class='del_thumbnail btn btn-default'><span class='fas fa-trash'></span> Sil</button>");
let _this = this;
removeButton.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
_this.removeFile(file);
});
file.previewElement.appendChild(removeButton);
});
this.on("error", function(file, message) {
console.log(message);
this.removeFile(file);
});
this.on('sending', function(file, xhr, formData) {
xhr.setRequestHeader("X-CSRFToken", csrftoken)
});
}
});
Dropzone.prototype.filesize = function(size) {
filesizecalculation(size);
};
function filesizecalculation(size) {
if (size < 1024 * 1024) {
return "<strong>" + (Math.round(Math.round(size / 1024) * 10) / 10) + " KB</strong>";
} else if (size < 1024 * 1024 * 1024) {
return "<strong>" + (Math.round((size / 1024 / 1024) * 10) / 10) + " MB</strong>";
} else if (size < 1024 * 1024 * 1024 * 1024) {
return "<strong>" + (Math.round((size / 1024 / 1024 / 1024) * 10) / 10) + " GB</strong>";
}
}
</script>
{% endblock body %}

View File

@ -22,5 +22,6 @@ urlpatterns = [
path('', TemplateView.as_view(template_name='store/index.html'), name='store_front_page'),
path('login/', views.CustomLoginView.as_view(), name='login'),
path('signup/', views.SignUpView.as_view(), name='signup'),
path('logout/', LogoutView.as_view(), name='logout')
path('logout/', LogoutView.as_view(), name='logout'),
path('upload/', views.FileFieldView.as_view(), name='upload'),
]

View File

@ -2,6 +2,11 @@ from django.shortcuts import render
from django.urls import reverse_lazy
from bootstrap_modal_forms.generic import BSModalCreateView, BSModalLoginView
from .forms import CustomUserCreationForm, CustomAuthenticationForm
from django.views.generic.edit import FormView
from .forms import FileFieldForm
import os
import PDMI.settings as settings
from .response import response_mimetype, JsonResponse
class SignUpView(BSModalCreateView):
form_class = CustomUserCreationForm
@ -14,3 +19,20 @@ class CustomLoginView(BSModalLoginView):
template_name = 'store/login.html'
success_message = 'Success: You were successfully logged in.'
extra_content = dict(success_url=reverse_lazy('index'))
class FileFieldView(FormView):
form_class = FileFieldForm
template_name = 'store/upload.html'
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
files = request.FILES.getlist('file')
if form.is_valid():
for f in files:
with open(os.path.join(settings.MEDIA_ROOT, f.name), 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
return JsonResponse({'form': True})
else:
return JsonResponse({'form': False})

View File

@ -19,6 +19,7 @@
<script src="{% static 'js/jquery.bootstrap.modal.forms.min.js' %}"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
{% block extra_static %}{% endblock extra_static %}
</head>
<body class="pt-5">
{% block navbar %}