Skip to content

Instantly share code, notes, and snippets.

@PythonicNinja
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PythonicNinja/ff4da3f44a727674eaf5 to your computer and use it in GitHub Desktop.
Save PythonicNinja/ff4da3f44a727674eaf5 to your computer and use it in GitHub Desktop.
upload files django angular
{% load i18n %}
<div class="form-images" nv-file-drop="" uploader="uploader">
<h3>{% trans "Upload images" %}</h3>
<div class="row">
<div class="col-md-3">
<div ng-show="uploader.isHTML5" class="">
<div class="my-drop-zone" nv-file-over="" uploader="uploader">
</div>
</div>
</div>
<div class="col-md-6">
<input type="file" nv-file-select="" uploader="uploader" multiple/><br/>
</div>
</div>
<div class="row" ng-show="uploader.queue.length">
<p>{% trans "images" %}: [[ uploader.queue.length ]]</p>
<table class="table">
<thead>
<tr>
<th width="50%">{% trans "image" %}</th>
<th ng-show="uploader.isHTML5">{% trans "progress" %}</th>
<th>{% trans "status" %}</th>
<th>{% trans "action" %}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in uploader.queue">
<td>
<!-- Image preview -->
<!--auto height-->
<!--<div ng-thumb="{ file: item.file, width: 100 }"></div>-->
<!--auto width-->
<div ng-show="uploader.isHTML5" ng-thumb="{ file: item._file, width: 200 }"></div>
<!--fixed width and height -->
<!--<div ng-thumb="{ file: item.file, width: 100, height: 100 }"></div>-->
</td>
<td ng-show="uploader.isHTML5">
<div class="progress" style="margin-bottom: 0;">
<div class="progress-bar" role="progressbar" ng-style="{ 'width': item.progress + '%' }"></div>
</div>
</td>
<td class="text-center">
<span ng-show="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
<span ng-show="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
<span ng-show="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
</td>
<td nowrap>
<button type="button" class="btn btn-success btn-xs" ng-click="item.upload()"
ng-disabled="item.isReady || item.isUploading || item.isSuccess">
<span class="glyphicon glyphicon-upload"></span>
</button>
<button type="button" class="btn btn-warning btn-xs" ng-click="item.cancel()"
ng-disabled="!item.isUploading">
<span class="glyphicon glyphicon-ban-circle"></span>
</button>
<button type="button" class="btn btn-danger btn-xs" ng-click="item.remove()">
<span class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>
</tbody>
</table>
<div>
<button type="button" class="btn btn-success pull-right" ng-click="uploader.uploadAll()"
ng-disabled="!uploader.getNotUploadedItems().length">
<span class="glyphicon glyphicon-upload"></span> {% trans "Upload all" %}
</button>
</div>
</div>
</div>
<script src="{% static "plugins/angular/angular.min.js" %}"></script>
<script src="{% static "plugins/angular/ui-bootstrap-tpls-0.11.0.js" %}"></script>
<script src="{% static "plugins/angular-file-upload/angular-file-upload.js" %}"></script>
<script src="{% static 'djangular/js/django-angular.js' %}"></script>
<script>angular.module('ng.django.urls').constant('patterns', {% load_djng_urls %});</script>
/**
* Created by vojtek.nowak on 11.09.2014.
*/
angular.module('WardrobeApp')
.controller('SellingInfoCtrl', function($scope, $http, $compile, $parse, WardrobeService, csrf_token, djangoForm, FileUploader, djangoUrl) {
$scope.modal_html = '';
$scope.$modal = '';
$scope.$btn = '';
var uploader = $scope.uploader = new FileUploader({
url: djangoUrl.reverse('wardrobe:add_product_sale_data1'),
method: 'PUT'
});
// FILTERS
uploader.filters.push({
name: 'imageFilter',
fn: function(item /*{File|FileLikeObject}*/, options) {
var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
}
});
$scope.showSellingInfoModal = function(arg_list){
$scope.$modal = $('#selling_info_modal');
var args = arg_list[0];
$scope.$btn = arg_list[1];
$scope.modal_html = args.form;
$scope.$digest();
$scope.form_name = args.form_name;
$scope.form_scope_prefix = args.scope_prefix;
$scope.form_data = $scope[$scope.form_scope_prefix];
$scope.$digest();
$scope.$modal.show('show');
};
$scope.$on("setSellingInfoHtml", function (event, args) {
$scope.showSellingInfoModal(args);
});
$scope.hideModal = function(){
$scope.$modal.slideUp();
};
$scope.toogleSaleBtn = function(){
//toogle btn
$scope.$btn.closest('.buttonwrap').fadeOut("slow");
$scope.$btn.closest('.product').find('.remove_form_sale').closest('.buttonwrap').fadeIn("slow");
};
$scope.incrementSaleNumbers = function(){
//update counter
var $sales_num = $('.sales-num');
$sales_num.find('p').text(parseInt($sales_num.find('p').text())+1);
};
uploader.onCompleteAll = function() {
$scope.incrementSaleNumbers();
$scope.toogleSaleBtn();
$scope.hideModal();
$scope.clearFormProcess();
};
$scope.clearFormProcess = function(){
uploader.formData = null;
};
$scope.submitForm = function() {
console.log('in submit', $scope.selling_info_form_data);
if ($scope.selling_info_form_data) {
$http.post(djangoUrl.reverse('wardrobe:add_product_sale_data1'), $scope.selling_info_form_data)
.success(function(out_data) {
if (!djangoForm.setErrors($scope.selling_info_form, out_data.errors)) {
console.log(out_data);
if(out_data.hasOwnProperty('selling_info') && out_data.selling_info.content_type && out_data.selling_info.id){
uploader.formData = [{
content_type: out_data.selling_info.content_type,
object_id: out_data.selling_info.id
}]
}
}
}).error(function() {
console.error('An error occured during submission');
});
}
return false;
};
});
class PutImageMixin(object):
def image_before_put(self):
pass
def image_process_object(self, request, data, file_obj, object_to_add):
pass
def image_get_object_to_add(self, data):
if data['object_id'] and data['content_type']:
object_id, content_type = int(data['object_id']), int(data['content_type'])
model_class = ContentType.objects.get_for_id(content_type).model_class()
object_to_add = get_object_or_404(model_class, pk=object_id)
return object_to_add
raise Http404
def put(self, request):
self.image_before_put()
data, file_obj = request.DATA, request.FILES['file']
object_to_add = self.image_get_object_to_add(data)
self.image_process_object(request, data, file_obj, object_to_add)
<div class="images" ng-show="uploader.formData">
{% include "includes/images/angular_add.html" %}
</div>
class AddProductSaleData1(PutImageMixin, APIView, FormView):
form_class = SellingInfoAngularForm
def post(self, request, **kwargs):
if request.is_ajax():
return self.ajax(request)
return super(AddProductSaleData1, self).post(request, **kwargs)
def ajax(self, request):
form = self.form_class(data=json.loads(request.body))
response_data = {'errors': form.errors}
if form.is_valid():
instance = form.save()
product = instance.product
# set selling info to false and only on added images
product.is_sale = False
product.save()
response_data['selling_info'] = SellingInfoSerializer(instance).data
return Response(response_data)
def image_process_object(self, request, data, file_obj, object_to_add):
image, __ = Image.objects.get_or_create(**{
'content_type': ContentType.objects.get(pk=int(data['content_type'])),
'object_id': int(data['object_id']),
'img': file_obj
})
self.serialized_img_object = ImageSerializer(image).data
object_to_add.product.is_sale = True
object_to_add.product.save()
def put(self, request):
super(AddProductSaleData1, self).put(request)
return Response(self.serialized_img_object)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment