Beispiel #1
0
    def save(self, *args, **kwargs):
        created = bool(self.pk is None)
        slugs = [self.slug] if self.slug else []
        self.name = clean_single_line_text(self.name)

        current_portal = self.portal or CosinnusPortal.get_current()
        unique_aware_slugify(self, 'name', 'slug', portal_id=current_portal)

        if not self.slug:
            raise ValidationError(_('Slug must not be empty.'))
        slugs.append(self.slug)
        # sanity check for missing media_tag:
        if not self.media_tag:
            from cosinnus.models.tagged import get_tag_object_model
            media_tag = get_tag_object_model()._default_manager.create()
            self.media_tag = media_tag

        # FIXME: This shouldn't be necessary, but throws an error if missing
        self.media_tag.save()

        # set portal to current
        if created and not self.portal:
            self.portal = CosinnusPortal.get_current()

        super(CosinnusOrganization, self).save(*args, **kwargs)

        self._clear_cache(slugs=slugs)
        # force rebuild the pk --> slug cache. otherwise when we query that, this group might not be in it
        self.__class__.objects.get_pks(force=True)

        self._portal_id = self.portal_id
        self._slug = self.slug
Beispiel #2
0
 def save(self, *args, **kwargs):
     created = bool(self.pk) == False
     unique_aware_slugify(self, 'title', 'slug', group=self.group)
     self.title = clean_single_line_text(self.title)
     if hasattr(self, '_media_tag_cache'):
         del self._media_tag_cache
     super(BaseTaggableObjectModel, self).save(*args, **kwargs)
     if not getattr(self, 'media_tag', None):
         self.media_tag = get_tag_object_model().objects.create()
         self.save()
     if created:
         pass
Beispiel #3
0
    def save(self, *args, **kwargs):
        created = bool(self.pk is None)
        slugs = [self.slug] if self.slug else []
        self.title = clean_single_line_text(self.title)

        unique_aware_slugify(self, 'title', 'slug', group_id=self.group_id)

        if not self.slug:
            raise ValidationError(_('Slug must not be empty.'))
        slugs.append(self.slug)

        super(CosinnusConferenceRoom, self).save(*args, **kwargs)

        # initialize/sync room-type-specific extras
        self.ensure_room_type_dependencies()
Beispiel #4
0
    def save(self, *args, **kwargs):
        created = bool(self.pk is None)
        slugs = [self.slug] if self.slug else []
        self.title = clean_single_line_text(self.title)

        current_portal = self.portal or CosinnusPortal.get_current()
        unique_aware_slugify(self, 'title', 'slug', portal_id=current_portal)

        if not self.slug:
            raise ValidationError(_('Slug must not be empty.'))
        slugs.append(self.slug)
        # sanity check for missing media_tag:
        if not self.media_tag:
            from cosinnus.models.tagged import get_tag_object_model
            media_tag = get_tag_object_model()._default_manager.create()
            self.media_tag = media_tag

        if created and not self.portal:
            # set portal to current
            self.portal = CosinnusPortal.get_current()

        super(CosinnusIdea, self).save(*args, **kwargs)

        self._clear_cache(slugs=slugs)
        # force rebuild the pk --> slug cache. otherwise when we query that, this group might not be in it
        self.__class__.objects.get_pks(force=True)

        self._portal_id = self.portal_id
        self._slug = self.slug

        if created:
            forum_slug = getattr(settings, 'NEWW_FORUM_GROUP_SLUG', None)
            if forum_slug:
                forum_group = get_object_or_None(
                    get_cosinnus_group_model(),
                    slug=forum_slug,
                    portal=CosinnusPortal.get_current())
                if forum_group:
                    # send creation signal
                    signals.idea_object_ceated.send(sender=self,
                                                    group=forum_group)
                    # we need to patch a group onto the idea, because notifications need a group
                    setattr(self, 'group', forum_group)
                    # the audience is empty because this is a moderator-only notification
                    cosinnus_notifications.idea_created.send(sender=self,
                                                             user=self.creator,
                                                             obj=self,
                                                             audience=[])
    def save(self, *args, **kwargs):
        created = bool(self.pk is None)
        slugs = [self.slug] if self.slug else []
        self.name = clean_single_line_text(self.name)

        current_portal = self.portal or CosinnusPortal().get_current()

        if not self.slug:
            raise ValidationError(_('Slug must not be empty.'))
        slugs.append(self.slug)

        # set portal to current
        if created and not self.portal:
            self.portal = current_portal

        super(CosinnusManagedTag, self).save(*args, **kwargs)
        self.clear_cache()
Beispiel #6
0
def file_upload_inline(request, group):
    """ Inline file upload to be called from jQuery FileUpload.
        @param request.on_success: Determines what kind of data will be sent back, and in cosinnus.JS, 
                                    determines what will be done with the data. Options:
            - 'add_to_select2' (default): Will render a select2 pill and in JS, append it to the attach-file select2 field.
            - 'refresh_page' will add a message to the request and in JS refresh the browser page
            - 'render_object' will render the single file template(s) and in JS append them to the file list """
    if not request.is_ajax() or not request.method=='POST':
        return HttpResponseNotAllowed(['POST'])
    
    on_success = request.POST.get('on_success', 'add_to_select2')
    direct_upload = request.POST.get('direct_upload', False)
    make_private = request.POST.get('private_upload', False)
    
    
    # resolve group either from the slug, or like the permission group mixin does ist
    # (group type needs to also be used for that=
    group = get_group_for_request(group, request)
    if not group:
        logger.error('No group found when trying to upload a file!', extra={'group_slug': group, 
            'request': request, 'path': request.path})
        return JSONResponse({'status': 'error', 'message': _('Internal Error: Group not Found')})
    
    # do permission checking using has_write_access(request.user, group)
    if not check_group_create_objects_access(group, request.user):
        logger.error('Permission error while uploading an attached file directly!', 
             extra={'user': request.user, 'request': request, 'path': request.path, 'group_slug': group})
        return JSONResponse({'status': 'error', 'message': _('Permission for upload denied')})
    
    # add any other required kwargs (group) and stuff correctly so the form can be saved
    post = request.POST
    post._mutable = True
    post.update({
        'group_id': group.id
    })
    
    
    base_upload_folder = None
    upload_to_attachment_folder = False
    if 'target_folder' in post:
        base_upload_folder = get_object_or_404(FileEntry, id=int(post.get('target_folder')))
    if not base_upload_folder:
        # check if the group has a folder with slug 'uploads' and if not, create one
        base_upload_folder = get_or_create_attachment_folder(group)
        upload_to_attachment_folder = True
    
    file_info_array = json.loads(post.get('file_info', '[]'))
    result_list = []
    for file_index, dict_file in enumerate(request.FILES.getlist('file')):
        upload_folder = None
        # unless we are uploading as attachment, see if we have any further folder info for this file
        if not upload_to_attachment_folder and len(file_info_array) > file_index:
            # get relative path for the ith file, it should be the same as in the FILES list
            relative_path = file_info_array[file_index]['relative_path']
            name = file_info_array[file_index]['name']
            if relative_path:
                # sanity check, file name in file info must match FILES file name
                if not name == dict_file._name:
                    logger.warn('File upload sanity check failed: File order of file with relative path info and FILES list did not match! (Upload may have sorted the user\'s file in the wrong folder)', extra={
                        'file_info': file_info_array, 'FILES_list': request.FILES.getlist('file')})
                upload_folder = _create_folders_for_path_string(base_upload_folder, relative_path)
                # switch mode to refresh page if we had at least one folder upload
                on_success = 'refresh_page'
                
        if not upload_folder:
            upload_folder = base_upload_folder
            
        single_file_dict = MultiValueDict({'file': [dict_file]})
        post.update({
            'title': clean_single_line_text(dict_file._name),
        })
        form = FileForm(post, single_file_dict, group=group, initial={})
        if form.is_valid():
            # form.instance is the FileEntry, not the media tag
            form.instance.group = group
            form.instance.creator = request.user
            form.instance.path = upload_folder.path
            form.instance._filesize = form.instance.file.file.size
            if not direct_upload:
                form.instance.no_notification = True # disable notifications on non-direct (attached, etc) uploads
            saved_file = form.save()
            
            # flag for uploading the file visible only to oneself, as used in message attachments
            if make_private:
                saved_file.media_tag.visibility = BaseTagObject.VISIBILITY_USER
                saved_file.media_tag.save()
                
            # render either for the file list or for the attached objects
            if on_success == 'render_object':
                context = {
                    'file': saved_file,
                    'do_highlight': True
                }
                result_list.append(render_to_string('cosinnus_file/single_file_detailed.html', context, request))
            else:
                # pipe the file into the select2 JSON representation to be displayed as select2 pill 
                pill_id, pill_html = build_attachment_field_result('cosinnus_file.FileEntry', saved_file)
                result_list.append({'text': pill_html, 'id': pill_id})
        else:
            logger.warn('Form error while uploading an attached file directly!', 
                 extra={'form.errors': form.errors, 'user': request.user, 'request': request, 
                        'path': request.path, 'group_slug': group})
            message = _('The uploaded file was invalid.')
            if form.forms['obj'].errors.get('file', None):
                message = form.forms['obj'].errors.get('file', None)
            return JSONResponse({'status': 'error', 'message': message})
            
    if result_list:
        if on_success == 'refresh_page':
            messages.success(request, ungettext('%(count)d File was added successfully.', '%(count)d Files were added successfully.', len(result_list)) % {'count': len(result_list)})
        
        
        return JSONResponse({'status': 'ok', 'on_success': on_success, 'data': result_list})
    else:
        return JSONResponse({'status': 'error', 'message': _('The file you uploaded was too large or the file type was not permitted to be uploaded!')})
Beispiel #7
0
 def save(self, *args, **kwargs):
     unique_aware_slugify(self, 'title', 'slug', group=self.group)
     self.title = clean_single_line_text(self.title)
     super(TodoList, self).save(*args, **kwargs)