def upload_attachment(request): if request.method != 'POST': return JsonResponse({ 'status': 'false', 'message': _('Only POST method is allowed'), }, status=400) if summernote_config['attachment_require_authentication']: if not request.user.is_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 > summernote_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 post(self, request, *args, **kwargs): authenticated = \ request.user.is_authenticated if django.VERSION >= (1, 10) \ else request.user.is_authenticated() if summernote_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 > summernote_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): summernote_config['attachment_storage_class'] = \ 'django.core.files.storage.DefaultStorage' from django_summernote.models import _get_attachment_storage 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 upload_attachment(request): if request.method != 'POST': return HttpResponseBadRequest(_('Only POST method is allowed')) if summernote_config['attachment_require_authentication']: if not request.user.is_authenticated(): return HttpResponseForbidden( _('Only authenticated users are allowed')) if not request.FILES.getlist('files'): return HttpResponseBadRequest(_('No files were requested')) # 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() file = file_size(file) attachment.file = file attachment.name = file.name if file.size > summernote_config['attachment_filesize_limit']: return HttpResponseBadRequest( _('File size exceeds the limit allowed and cannot be saved' )) # calling save method with attachment parameters as kwargs attachment.save(**kwargs) attachments.append(attachment) return render(request, 'django_summernote/upload_attachment.json', { 'attachments': attachments, }) except IOError: return HttpResponseServerError(_('Failed to save attachment'))
def upload_attachment(request): if request.method != 'POST': return HttpResponseBadRequest('Only POST method is allowed') if summernote_config['attachment_require_authentication']: if not request.user.is_authenticated(): return HttpResponseForbidden('Only authenticated users are allowed') if not request.FILES.getlist('files'): return HttpResponseBadRequest('No files were requested') 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 > summernote_config['attachment_filesize_limit']: return HttpResponseBadRequest( 'File size exceeds the limit allowed and cannot be saved' ) # remove unnecessary CSRF token, if found request.POST.pop("csrfmiddlewaretoken", None) kwargs = request.POST # calling save method with attachment parameters as kwargs attachment.save(**kwargs) attachments.append(attachment) return render(request, 'django_summernote/upload_attachment.json', { 'attachments': attachments, }) except IOError: return HttpResponseServerError('Failed to save attachment')
def test_attachment_with_bad_storage(self): from django.core.exceptions import ImproperlyConfigured # ValueError summernote_config['attachment_storage_class'] = \ 'wow_no_dot_storage_class_name' with self.assertRaises(ImproperlyConfigured): from django_summernote import models reload(models) # ImportError summernote_config['attachment_storage_class'] = \ 'wow.such.fake.storage' with self.assertRaises(ImproperlyConfigured): from django_summernote import models reload(models) # AttributeError 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 django_summernote.models import Attachment 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 summernote_config['attachment_model'] = \ 'wow_no_dot_model_designation' with self.assertRaises(ImproperlyConfigured): get_attachment_model() # LookupError 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 summernote_config['attachment_model'] = \ 'auth.User' with self.assertRaises(ImproperlyConfigured): get_attachment_model()
from django.contrib import admin from django_summernote.settings import get_attachment_model from dynamic_preferences.admin import PerInstancePreferenceAdmin from dynamic_preferences.models import GlobalPreferenceModel from .models import TournamentPreferenceModel # ============================================================================== # Preferences # ============================================================================== @admin.register(TournamentPreferenceModel) class TournamentPreferenceAdmin(PerInstancePreferenceAdmin): pass admin.site.unregister(GlobalPreferenceModel) # We don't use the attachment model; so hide it in the admin area admin.site.unregister(get_attachment_model())
if self.summernote_fields == '__all__': if isinstance(db_field, models.TextField): kwargs['widget'] = self.summernote_widget else: if db_field.name in self.summernote_fields: kwargs['widget'] = self.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)
def formfield_for_dbfield(self, db_field, *args, **kwargs): if self.summernote_fields == '__all__': if isinstance(db_field, models.TextField): kwargs['widget'] = self.summernote_widget else: if db_field.name in self.summernote_fields: kwargs['widget'] = self.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)