class FileAttachmentAdmin(AttachmentAdmin): model = get_attachment_model() extra = 0 list_display = [ 'id', 'name', 'category', 'file', 'created_at', 'modified_at', ] list_display_links = [ 'id', ] search_fields = [ 'id', 'name', 'category', 'tag', ] fields = [ 'id', 'uuid', 'get_attachment_url', 'name', 'category', 'tag', 'file', 'uploaded', ] readonly_fields = [ 'id', 'uuid', 'get_attachment_url', 'uploaded', ] form = AttachmentAdminForm list_filter = ( 'category', 'tag', ) def get_attachment_url(self, obj): if obj.uuid: url = reverse('attachment:file', kwargs={'uuid': obj.uuid}) return format_html('<a href="{}" target="_blank">{}</a>', url, url) return None get_attachment_url.short_description = "attachment url"
def post(self, request, *args, **kwargs): authenticated = \ request.user.is_authenticated if django_version >= (1, 10) \ else request.user.is_authenticated() if config['attachment_require_authentication'] and \ not authenticated: return JsonResponse({ 'status': 'false', 'message': _('Only authenticated users are allowed'), }, status=403) if not request.FILES.getlist('files'): return JsonResponse({ 'status': 'false', 'message': _('No files were requested'), }, status=400) # remove unnecessary CSRF token, if found kwargs = request.POST.copy() kwargs.pop("csrfmiddlewaretoken", None) try: attachments = [] for file in request.FILES.getlist('files'): # create instance of appropriate attachment class klass = get_attachment_model() attachment = klass() attachment.file = file attachment.name = file.name if file.size > config['attachment_filesize_limit']: return JsonResponse({ 'status': 'false', 'message': _('File size exceeds the limit allowed and cannot be saved'), }, status=400) # calling save method with attachment parameters as kwargs attachment.save(**kwargs) # choose relative/absolute url by config attachment.url = attachment.file.url if config['attachment_absolute_uri']: attachment.url = request.build_absolute_uri(attachment.url) attachments.append(attachment) return HttpResponse(render_to_string('django_summernote/upload_attachment.json', { 'attachments': attachments, }), content_type='application/json') except IOError: return JsonResponse({ 'status': 'false', 'message': _('Failed to save attachment'), }, status=500)
def post(self, request, *args, **kwargs): authenticated = \ request.user.is_authenticated if django_version >= (1, 10) \ else request.user.is_authenticated() if config['attachment_require_authentication'] and \ not authenticated: return JsonResponse({ 'status': 'false', 'message': _('Only authenticated users are allowed'), }, status=403) if not request.FILES.getlist('files'): return JsonResponse({ 'status': 'false', 'message': _('No files were requested'), }, status=400) # remove unnecessary CSRF token, if found kwargs = request.POST.copy() kwargs.pop("csrfmiddlewaretoken", None) try: attachments = [] for file in request.FILES.getlist('files'): # create instance of appropriate attachment class klass = get_attachment_model() attachment = klass() attachment.file = file attachment.name = file.name if file.size > config['attachment_filesize_limit']: return JsonResponse({ 'status': 'false', 'message': _('File size exceeds the limit allowed and cannot be saved'), }, status=400) # calling save method with attachment parameters as kwargs attachment.save(**kwargs) attachments.append(attachment) return HttpResponse(render_to_string('django_summernote/upload_attachment.json', { 'attachments': attachments, }), content_type='application/json') except IOError: return JsonResponse({ 'status': 'false', 'message': _('Failed to save attachment'), }, status=500)
def test_attachment_with_custom_storage(self): self.summernote_config['attachment_storage_class'] = \ 'django.core.files.storage.DefaultStorage' file_field = get_attachment_model()._meta.get_field('file') original_storage = file_field.storage file_field.storage = get_attachment_storage() url = reverse('django_summernote-upload_attachment') with open(IMAGE_FILE, 'rb') as fp: response = self.client.post(url, {'files': [fp]}) self.assertEqual(response.status_code, 200) file_field.storage = original_storage
def test_attachment_with_custom_storage(self): self.summernote_config['attachment_storage_class'] = \ 'django.core.files.storage.DefaultStorage' file_field = get_attachment_model()._meta.get_field('file') original_storage = file_field.storage file_field.storage = get_attachment_storage() url = reverse('django_summernote-upload_attachment') with open(__file__, 'rb') as fp: response = self.client.post(url, {'files': [fp]}) self.assertEqual(response.status_code, 200) file_field.storage = original_storage
def test_attachment_with_bad_storage(self): from django.core.exceptions import ImproperlyConfigured # ValueError self.summernote_config['attachment_storage_class'] = \ 'wow_no_dot_storage_class_name' with self.assertRaises(ImproperlyConfigured): from django_summernote import models reload(models) # ImportError self.summernote_config['attachment_storage_class'] = \ 'wow.such.fake.storage' with self.assertRaises(ImproperlyConfigured): from django_summernote import models reload(models) # AttributeError self.summernote_config['attachment_storage_class'] = \ 'django.core.files.storage.DogeStorage' with self.assertRaises(ImproperlyConfigured): from django_summernote import models reload(models) # IOError with patching storage class from dummyplug.storage import IOErrorStorage file_field = get_attachment_model()._meta.get_field('file') original_storage = file_field.storage file_field.storage = IOErrorStorage() url = reverse('django_summernote-upload_attachment') with open(IMAGE_FILE, 'rb') as fp: response = self.client.post(url, {'files': [fp]}) self.assertNotEqual(response.status_code, 200) file_field.storage = original_storage
def test_attachment_with_bad_storage(self): from django.core.exceptions import ImproperlyConfigured # ValueError self.summernote_config['attachment_storage_class'] = \ 'wow_no_dot_storage_class_name' with self.assertRaises(ImproperlyConfigured): from django_summernote import models reload(models) # ImportError self.summernote_config['attachment_storage_class'] = \ 'wow.such.fake.storage' with self.assertRaises(ImproperlyConfigured): from django_summernote import models reload(models) # AttributeError self.summernote_config['attachment_storage_class'] = \ 'django.core.files.storage.DogeStorage' with self.assertRaises(ImproperlyConfigured): from django_summernote import models reload(models) # IOError with patching storage class from dummyplug.storage import IOErrorStorage file_field = get_attachment_model()._meta.get_field('file') original_storage = file_field.storage file_field.storage = IOErrorStorage() url = reverse('django_summernote-upload_attachment') with open(__file__, 'rb') as fp: response = self.client.post(url, {'files': [fp]}) self.assertNotEqual(response.status_code, 200) file_field.storage = original_storage
def test_get_attachment_model(self): from django.core.exceptions import ImproperlyConfigured # ValueError self.summernote_config['attachment_model'] = \ 'wow_no_dot_model_designation' with self.assertRaises(ImproperlyConfigured): get_attachment_model() # LookupError self.summernote_config['attachment_model'] = \ 'wow.not.installed.app.model' with self.assertRaises(ImproperlyConfigured): get_attachment_model() # Ensures proper inheritance, using built-in User class to test self.summernote_config['attachment_model'] = \ 'auth.User' with self.assertRaises(ImproperlyConfigured): get_attachment_model()
def post(self, request, *args, **kwargs): authenticated = \ request.user.is_authenticated if django_version >= (1, 10) \ else request.user.is_authenticated() if config['disable_attachment']: logger.error( 'User<%s:%s> tried to use disabled attachment module.', getattr(request.user, 'pk', None), request.user) return JsonResponse( { 'status': 'false', 'message': _('Attachment module is disabled'), }, status=403) if config['attachment_require_authentication'] and \ not authenticated: return JsonResponse( { 'status': 'false', 'message': _('Only authenticated users are allowed'), }, status=403) if not request.FILES.getlist('files'): return JsonResponse( { 'status': 'false', 'message': _('No files were requested'), }, status=400) # remove unnecessary CSRF token, if found kwargs = request.POST.copy() kwargs.pop('csrfmiddlewaretoken', None) for file in request.FILES.getlist('files'): form = UploadForm(files={ 'file': file, }) if not form.is_valid(): logger.error('User<%s:%s> tried to upload non-image file.', getattr(request.user, 'pk', None), request.user) return JsonResponse( { 'status': 'false', 'message': ''.join(form.errors['file']), }, status=400) try: attachments = [] for file in request.FILES.getlist('files'): # create instance of appropriate attachment class klass = get_attachment_model() attachment = klass() attachment.file = file if file.size > config['attachment_filesize_limit']: return JsonResponse( { 'status': 'false', 'message': _('File size exceeds the limit allowed and cannot be saved' ), }, status=400) # calling save method with attachment parameters as kwargs attachment.save(**kwargs) # choose relative/absolute url by config attachment.url = attachment.file.url if config['attachment_absolute_uri']: attachment.url = request.build_absolute_uri(attachment.url) attachments.append(attachment) return HttpResponse(render_to_string( 'django_summernote/upload_attachment.json', { 'attachments': attachments, }), content_type='application/json') except IOError: return JsonResponse( { 'status': 'false', 'message': _('Failed to save attachment'), }, status=500)
from django.contrib import admin # Register your models here. from django_summernote.utils import get_attachment_model """ """ admin.site.site_url = "/gestion" admin.site.site_header = "CSU Inventario" admin.site.site_title = "CSU Inventario" admin.site.index_title = "CSU Inventario" admin.site.unregister(get_attachment_model())
class Meta: model = get_attachment_model() fields = '__all__'
if self.summernote_fields == '__all__': if isinstance(db_field, models.TextField): kwargs['widget'] = summernote_widget else: if db_field.name in self.summernote_fields: kwargs['widget'] = summernote_widget return super(SummernoteModelAdminMixin, self).formfield_for_dbfield(db_field, *args, **kwargs) class SummernoteInlineModelAdmin(SummernoteModelAdminMixin, InlineModelAdmin): pass class SummernoteModelAdmin(SummernoteModelAdminMixin, admin.ModelAdmin): pass class AttachmentAdmin(admin.ModelAdmin): list_display = ['name', 'file', 'uploaded'] search_fields = ['name'] ordering = ('-id', ) def save_model(self, request, obj, form, change): obj.name = obj.file.name if (not obj.name) else obj.name super(AttachmentAdmin, self).save_model(request, obj, form, change) admin.site.register(get_attachment_model(), AttachmentAdmin)
if self.summernote_fields == '__all__': if isinstance(db_field, models.TextField): kwargs['widget'] = summernote_widget else: if db_field.name in self.summernote_fields: kwargs['widget'] = summernote_widget return super(SummernoteModelAdminMixin, self).formfield_for_dbfield(db_field, *args, **kwargs) class SummernoteInlineModelAdmin(SummernoteModelAdminMixin, InlineModelAdmin): pass class SummernoteModelAdmin(SummernoteModelAdminMixin, admin.ModelAdmin): pass class AttachmentAdmin(admin.ModelAdmin): list_display = ['name', 'file', 'uploaded'] search_fields = ['name'] ordering = ('-id',) def save_model(self, request, obj, form, change): obj.name = obj.file.name if (not obj.name) else obj.name super(AttachmentAdmin, self).save_model(request, obj, form, change) admin.site.register(get_attachment_model(), AttachmentAdmin)