Enable DnD for Company image

- Can actually use the existing form to do partial upload!
- Generecise the drag-and-drop upload function
- Remove some (now unnecessary) Python View code
This commit is contained in:
Oliver Walters 2019-05-07 14:47:31 +10:00
parent 39672d4e23
commit dcbd5d819c
6 changed files with 81 additions and 135 deletions

View File

@ -148,7 +148,6 @@ def MakeBarcode(object_type, object_id, object_url, data={}):
data['id'] = object_id
data['url'] = object_url
data['tool'] = 'InvenTree'
data['generated'] = str(datetime.now().date())
return json.dumps(data, sort_keys=True)

View File

@ -7,15 +7,17 @@
<div class="row">
<div class="col-sm-6">
<div class="media">
<div class="media-left">
<img class="part-thumb" id='company-thumb'
{% if company.image %}
src="{{ company.image.url }}"
{% else %}
src="{% static 'img/blank_image.png' %}"
{% endif %}/>
</div>
<div class='media-body'>
<div class='media-left'>
<div class='dropzone' id='company-thumb'>
<img class="part-thumb"
{% if company.image %}
src="{{ company.image.url }}"
{% else %}
src="{% static 'img/blank_image.png' %}"
{% endif %}/>
</div>
</div>
<div class='media-body'>
<h4>{{ company.name }}</h4>
<p>{{ company.description }}</p>
</div>
@ -68,6 +70,17 @@
{% block js_ready %}
enableDragAndDrop(
"#company-thumb",
"{% url 'company-image' company.id %}",
{
label: 'image',
success: function(data, status, xhr) {
location.reload();
}
}
);
$("#company-thumb").click(function() {
launchModalForm(
"{% url 'company-image' company.id %}",

View File

@ -13,17 +13,14 @@
<div class="col-sm-6">
<div class="media">
<div class="media-left">
<form id='upload-photo' method='post' action="{% url 'part-image-upload' part.id %}">
<div class='dropzone' id='part-thumb'>
<div class='dropzone' id='part-thumb'>
<img class="part-thumb"
{% if part.image %}
src="{{ part.image.url }}"
{% else %}
src="{% static 'img/blank_image.png' %}"
{% endif %}/>
</div>
{% csrf_token %}
</form>
</div>
</div>
<div class="media-body">
<h4>
@ -102,34 +99,16 @@
{% block js_ready %}
{{ block.super }}
$('#part-thumb').on('drop', function(event) {
var transfer = event.originalEvent.dataTransfer;
var formData = new FormData();
if (isFileTransfer(transfer)) {
formData.append('image_file', transfer.files[0]);
} else if (isOnlineTransfer(transfer)) {
formData.append('image_url', getImageUrlFromTransfer(transfer));
} else {
console.log('Unknown transfer');
return;
}
inventreeFormDataUpload(
"{% url 'part-image-upload' part.id %}",
formData,
{
success: function(data, status, xhr) {
location.reload();
},
error: function(xhr, status, error) {
showAlertDialog('Error uploading image', renderErrorMessage(xhr));
}
enableDragAndDrop(
'#part-thumb',
"{% url 'part-image' part.id %}",
{
label: 'image',
success: function(data, status, xhr) {
location.reload();
}
);
});
}
);
$("#show-qr-code").click(function() {
launchModalForm(

View File

@ -47,9 +47,6 @@ part_detail_urls = [
url(r'^qr_code/?', views.PartQRCode.as_view(), name='part-qr'),
# Drag-and-drop thumbnail upload
url(r'^thumbnail-upload/?', views.UploadPartImage.as_view(), name='part-image-upload'),
# Normal thumbnail with form
url(r'^thumbnail/?', views.PartImage.as_view(), name='part-image'),

View File

@ -272,96 +272,6 @@ class PartImage(AjaxUpdateView):
}
class UploadPartImage(AjaxView):
""" View for uploading a Part image via AJAX request.
e.g. via a "drag and drop" event.
There are two ways to upload a file:
1. Attach an image file as request.FILES['image_file']
- Image is validated saved
- Part object is saved
2. Attach an iamge URL as request.POST['image_url']
NOT YET IMPLEMENTED
- Image URL is valiated
- Image is downloaded and validated
- Part object is saved
"""
model = Part
def post(self, request, *args, **kwargs):
response = {}
status = 200
try:
part = Part.objects.get(pk=kwargs.get('pk'))
except Part.DoesNotExist:
response['error'] = 'Part not found'
return JsonResponse(response, status=404)
# Direct image upload
if 'image_file' in request.FILES:
image = request.FILES['image_file']
if TestIfImage(image):
part.image = image
part.clean()
part.save()
response['success'] = 'File was uploaded successfully'
status = 200
else:
response['error'] = 'Not a valid image file'
status = 400
return JsonResponse(response, status=status)
elif 'image_url' in request.POST:
image_url = str(request.POST['image_url']).split('?')[0]
validator = URLValidator()
try:
validator(image_url)
except ValidationError:
response['error'] = 'Invalid image URL'
response['url'] = image_url
return JsonResponse(response, status=400)
# Test the the URL at least looks like an image
if not TestIfImageURL(image_url):
response['error'] = 'Invalid image URL'
response['url'] = image_url
return JsonResponse(response, status=400)
response['error'] = 'Cannot download cross-site images (yet)'
response['url'] = image_url
response['apology'] = 'deepest'
return JsonResponse(response, status=400)
# TODO - Attempt to download the image file here
"""
head = requests.head(url, stream=True, headers={'User-agent': 'Mozilla/5.0'})
if head.headers['Content-Length'] < SOME_MAX_LENGTH:
image = requests.get(url, stream=True, headers={'User-agent': 'Mozilla/5.0'})
file = io.BytesIO(image.raw.read())
- Save the file?
"""
# Default response
return JsonResponse(response, status=status)
class PartEdit(AjaxUpdateView):
""" View for editing Part object """

View File

@ -69,4 +69,52 @@ function getImageUrlFromTransfer(transfer) {
console.log('Image URL: ' + url);
return url;
}
function enableDragAndDrop(element, url, options) {
/* Enable drag-and-drop file uploading for a given element.
Params:
element - HTML element lookup string e.g. "#drop-div"
url - URL to POST the file to
options - object with following possible values:
label - Label of the file to upload (default='file')
success - Callback function in case of success
error - Callback function in case of error
*/
$(element).on('drop', function(event) {
var transfer = event.originalEvent.dataTransfer;
var label = options.label || 'file';
var formData = new FormData();
if (isFileTransfer(transfer)) {
formData.append(label, transfer.files[0]);
inventreeFormDataUpload(
url,
formData,
{
success: function(data, status, xhr) {
console.log('Uploaded file via drag-and-drop');
if (options.success) {
options.success(data, status, xhr);
}
},
error: function(xhr, status, error) {
console.log('File upload failed');
if (options.error) {
options.error(xhr, status, error);
}
}
}
);
} else {
console.log('Ignoring drag-and-drop event (not a file)');
}
});
}