class IsEnabledMixin(object): """ Mixin to check if forums is enabled. """ @method_decorator(is_enabled('forums')) def dispatch(self, request, *args, **kwargs): return super(IsEnabledMixin, self).dispatch(request, *args, **kwargs)
class FileTinymceCreateView(CreateView): model = File #fields = ("file",) template_name_suffix = '_tinymce_upload_form' form_class = TinymceUploadForm @method_decorator(is_enabled('files')) @method_decorator(login_required) @method_decorator(csrf_protect) def dispatch(self, request, *args, **kwargs): if not has_perm(request.user, 'files.add_file'): return HttpResponseForbidden() return super(FileTinymceCreateView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(FileTinymceCreateView, self).get_context_data(**kwargs) context['app_label'] = self.request.GET.get('app_label', '') context['model'] = self.request.GET.get('model', '') context['object_id'] = self.request.GET.get('object_id', 0) context['max_file_size'] = get_max_file_upload_size(file_module=True) context['upload_type'] = self.request.GET.get('type', '') context['accept_file_types'] = '|'.join( x[1:] for x in get_allowed_upload_file_exts(context['upload_type'])) return context def form_valid(self, form): app_label = self.request.POST['app_label'] model = unicode(self.request.POST['model']).lower() try: object_id = int(self.request.POST['object_id']) except: object_id = 0 self.object = form.save() self.object.object_id = object_id try: self.object.content_type = ContentType.objects.get( app_label=app_label, model=model) except ContentType.DoesNotExist: self.object.content_type = None self.object.creator = self.request.user self.object.creator_username = self.request.user.username self.object.owner = self.request.user self.object.owner_username = self.request.user.username self.object.save() f = self.object.file name = self.object.basename() if self.object.f_type == 'image': thumbnail_url = reverse( 'file', args=[self.object.id, '50x50', 'crop', '88']) else: thumbnail_url = self.object.icon() # truncate name to 20 chars length if len(name) > 20: name = name[:17] + '...' data = { 'files': [{ 'url': self.object.get_absolute_url(), 'name': name, 'type': mimetypes.guess_type(f.path)[0] or 'image/png', 'thumbnailUrl': thumbnail_url, 'size': self.object.get_size(), 'deleteUrl': reverse('file.delete', args=[self.object.pk]), 'deleteType': 'DELETE', }] } return JsonResponse(data) def form_invalid(self, form): data = json.loads(form.errors.as_json()).values() errors = '. '.join([x[0]['message'] for x in data]) data = { 'files': [{ 'errors': errors, }] } return JsonResponse(data)