Python django.core.files.storage.default_storage.delete() Examples

The following are 30 code examples of django.core.files.storage.default_storage.delete(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.files.storage.default_storage , or try the search function .
Example #1
Source File: forms.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 6 votes vote down vote up
def save(self, commit=True):
        instance = super().save(commit=False)
        picture_path = self.cleaned_data["picture_path"]
        if picture_path:
            temporary_image_path = os.path.join("temporary-uploads", picture_path)
            file_obj = default_storage.open(temporary_image_path)
            instance.picture.save(picture_path, file_obj, save=False)
            default_storage.delete(temporary_image_path)
        latitude = self.cleaned_data["latitude"]
        longitude = self.cleaned_data["longitude"]
        if latitude is not None and longitude is not None:
            instance.set_geoposition(longitude=longitude, latitude=latitude)
        if commit:
            instance.save()
            self.save_m2m()
        return instance 
Example #2
Source File: models.py    From edx-enterprise with GNU Affero General Public License v3.0 6 votes vote down vote up
def logo_path(instance, filename):
    """
    Delete the file if it already exist and returns the enterprise customer logo image path.

    Arguments:
        instance (:class:`.EnterpriseCustomerBrandingConfiguration`): EnterpriseCustomerBrandingConfiguration object
        filename (str): file to upload

    Returns:
        path: path of image file e.g. enterprise/branding/<model.id>/<model_id>_logo.<ext>.lower()

    """
    extension = os.path.splitext(filename)[1].lower()
    instance_id = str(instance.id)
    fullname = os.path.join("enterprise/branding/", instance_id, instance_id + "_logo" + extension)
    if default_storage.exists(fullname):
        default_storage.delete(fullname)
    return fullname 
Example #3
Source File: forms.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 6 votes vote down vote up
def save(self, commit=True):
        instance = super().save(commit=False)
        picture_path = self.cleaned_data["picture_path"]
        if picture_path:
            temporary_image_path = os.path.join("temporary-uploads", picture_path)
            file_obj = default_storage.open(temporary_image_path)
            instance.picture.save(picture_path, file_obj, save=False)
            default_storage.delete(temporary_image_path)
        latitude = self.cleaned_data["latitude"]
        longitude = self.cleaned_data["longitude"]
        if latitude is not None and longitude is not None:
            instance.set_geoposition(longitude=longitude, latitude=latitude)
        if commit:
            instance.save()
            self.save_m2m()
        return instance 
Example #4
Source File: test_attachment.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_create_thumbnails_command(self):
        call_command("create_image_thumbnails")
        for attachment in Attachment.objects.filter(instance=self.instance):
            filename = attachment.media_file.name.replace('.jpg', '')
            for size in ['small', 'medium', 'large']:
                thumbnail = '%s-%s.jpg' % (filename, size)
                self.assertTrue(
                    default_storage.exists(thumbnail))
        check_datetime = datetime.now()
        # replace or regenerate thumbnails if they exist
        call_command("create_image_thumbnails", force=True)
        for attachment in Attachment.objects.filter(instance=self.instance):
            filename = attachment.media_file.name.replace('.jpg', '')
            for size in ['small', 'medium', 'large']:
                thumbnail = '%s-%s.jpg' % (filename, size)
                self.assertTrue(
                    default_storage.exists(thumbnail))
                self.assertTrue(
                    default_storage.modified_time(thumbnail) > check_datetime)
                default_storage.delete(thumbnail) 
Example #5
Source File: forms.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 6 votes vote down vote up
def save(self, commit=True):
        instance = super().save(commit=False)
        picture_path = self.cleaned_data["picture_path"]
        if picture_path:
            temporary_image_path = os.path.join("temporary-uploads", picture_path)
            file_obj = default_storage.open(temporary_image_path)
            instance.picture.save(picture_path, file_obj, save=False)
            default_storage.delete(temporary_image_path)
        latitude = self.cleaned_data["latitude"]
        longitude = self.cleaned_data["longitude"]
        if latitude is not None and longitude is not None:
            instance.set_geoposition(longitude=longitude, latitude=latitude)
        if commit:
            instance.save()
            self.save_m2m()
        return instance 
Example #6
Source File: forms.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 6 votes vote down vote up
def save(self, commit=True):
        instance = super().save(commit=False)
        picture_path = self.cleaned_data["picture_path"]
        if picture_path:
            temporary_image_path = os.path.join("temporary-uploads", picture_path)
            file_obj = default_storage.open(temporary_image_path)
            instance.picture.save(picture_path, file_obj, save=False)
            default_storage.delete(temporary_image_path)
        latitude = self.cleaned_data["latitude"]
        longitude = self.cleaned_data["longitude"]
        if latitude is not None and longitude is not None:
            instance.set_geoposition(longitude=longitude, latitude=latitude)
        if commit:
            instance.save()
            self.save_m2m()
        return instance 
Example #7
Source File: forms.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def save(self):
        photo = super(OrganizationForm, self).save()
        x = self.cleaned_data.get('x')
        y = self.cleaned_data.get('y')
        w = self.cleaned_data.get('width')
        h = self.cleaned_data.get('height')

        if x is not None and y is not None:
            image = Image.open(photo.logo)
            cropped_image = image.crop((x, y, w+x, h+y))
            resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
            # resized_image.save(photo.logo.path)
            resized_image_file = StringIO.StringIO()
            mime = mimetypes.guess_type(photo.logo.name)[0]
            plain_ext = mime.split('/')[1]
            resized_image.save(resized_image_file, plain_ext)
            default_storage.delete(photo.logo.name)
            default_storage.save(photo.logo.name, ContentFile(resized_image_file.getvalue()))
            resized_image_file.close()
        return photo 
Example #8
Source File: models.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def delete(self, *args, **kwargs):
        from django.core.files.storage import default_storage

        if self.picture:
            with contextlib.suppress(FileNotFoundError):
                default_storage.delete(self.picture_desktop.path)
                default_storage.delete(self.picture_tablet.path)
                default_storage.delete(self.picture_mobile.path)
            self.picture.delete()
        super().delete(*args, **kwargs) 
Example #9
Source File: models.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def delete(self, *args, **kwargs):
        from django.core.files.storage import default_storage

        if self.picture:
            with contextlib.suppress(FileNotFoundError):
                default_storage.delete(self.picture_desktop.path)
                default_storage.delete(self.picture_tablet.path)
                default_storage.delete(self.picture_mobile.path)
            self.picture.delete()
        super().delete(*args, **kwargs) 
Example #10
Source File: models.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def delete(self, *args, **kwargs):
        from django.core.files.storage import default_storage
        if self.picture:
            with contextlib.suppress(FileNotFoundError):
                default_storage.delete(self.picture_social.path)
                default_storage.delete(self.picture_large.path)
                default_storage.delete(self.picture_thumbnail.path)
            self.picture.delete()
        super().delete(*args, **kwargs) 
Example #11
Source File: models.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def delete(self, *args, **kwargs):
        from django.core.files.storage import default_storage

        if self.picture:
            with contextlib.suppress(FileNotFoundError):
                default_storage.delete(self.picture_desktop.path)
                default_storage.delete(self.picture_tablet.path)
                default_storage.delete(self.picture_mobile.path)
            self.picture.delete()
        super().delete(*args, **kwargs) 
Example #12
Source File: models.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def delete(self, *args, **kwargs):
        from django.core.files.storage import default_storage
        if self.picture:
            with contextlib.suppress(FileNotFoundError):
                default_storage.delete(self.picture_social.path)
                default_storage.delete(self.picture_large.path)
                default_storage.delete(self.picture_thumbnail.path)
            self.picture.delete()
        super().delete(*args, **kwargs) 
Example #13
Source File: models.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def delete(self, *args, **kwargs):
        from django.core.files.storage import default_storage
        if self.picture:
            with contextlib.suppress(FileNotFoundError):
                default_storage.delete(self.picture_social.path)
                default_storage.delete(self.picture_large.path)
                default_storage.delete(self.picture_thumbnail.path)
            self.picture.delete()
        super().delete(*args, **kwargs) 
Example #14
Source File: models.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def delete(self, *args, **kwargs):
        from django.core.files.storage import default_storage
        if self.picture:
            with contextlib.suppress(FileNotFoundError):
                default_storage.delete(self.picture_social.path)
                default_storage.delete(self.picture_large.path)
                default_storage.delete(self.picture_thumbnail.path)
            self.picture.delete()
        super().delete(*args, **kwargs) 
Example #15
Source File: models.py    From django-flowjs with MIT License 5 votes vote down vote up
def flow_file_chunk_delete(sender, instance, **kwargs):
    """
    Remove file when chunk is deleted
    """
    instance.file.delete(False) 
Example #16
Source File: models.py    From django-flowjs with MIT License 5 votes vote down vote up
def flow_file_delete(sender, instance, **kwargs):
    """
    Remove files on delete if is activated in settings
    """
    if FLOWJS_REMOVE_FILES_ON_DELETE:
        default_storage.delete(instance.path) 
Example #17
Source File: models.py    From django-flowjs with MIT License 5 votes vote down vote up
def _delete_chunks(self):
        for chunk in self.chunks.all():
            chunk.delete() 
Example #18
Source File: tests.py    From django-oss-storage with MIT License 5 votes vote down vote up
def test_delete(self):
        with self.save_file():
            self.assertTrue(default_storage.exists("test.txt"))
            default_storage.delete("test.txt")
        self.assertFalse(default_storage.exists("test.txt")) 
Example #19
Source File: tests.py    From django-oss-storage with MIT License 5 votes vote down vote up
def save_file(self, name="test.txt", content=b"test", storage=default_storage):
        logging.info("name: %s", name)
        logging.debug("content: %s", content)
        name = storage.save(name, ContentFile(content,name))
        try:
            yield name
        finally:
            storage.delete(name)
            pass 
Example #20
Source File: models.py    From edx-enterprise with GNU Affero General Public License v3.0 5 votes vote down vote up
def unenroll(self, course_run_id):
        """
        Unenroll a user from a course track.
        """
        enrollment_api_client = EnrollmentApiClient()
        if enrollment_api_client.unenroll_user_from_course(self.username, course_run_id):
            EnterpriseCourseEnrollment.objects.filter(enterprise_customer_user=self, course_id=course_run_id).delete()
            return True
        return False 
Example #21
Source File: models.py    From edx-enterprise with GNU Affero General Public License v3.0 5 votes vote down vote up
def clear_pending_registration(self, email, *course_ids):
        """
        Clear pending enrollments for the user in the given courses.

        Args:
            email: The email address which may have previously been used.
            course_ids: An iterable containing any number of course IDs.
        """
        try:
            pending_ecu = PendingEnterpriseCustomerUser.objects.get(user_email=email, enterprise_customer=self)
        except PendingEnterpriseCustomerUser.DoesNotExist:
            pass
        else:
            PendingEnrollment.objects.filter(user=pending_ecu, course_id__in=course_ids).delete() 
Example #22
Source File: checks.py    From django-watchman with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _check_storage():
    filename = joinpath(watchman_settings.WATCHMAN_STORAGE_PATH, 'django-watchman-{}.txt'.format(uuid.uuid4()))
    content = b'django-watchman test file'
    path = default_storage.save(filename, ContentFile(content))
    default_storage.size(path)
    default_storage.open(path).read()
    default_storage.delete(path)
    return {"ok": True} 
Example #23
Source File: checks.py    From django-watchman with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _check_cache(cache_name):
    key = 'django-watchman-{}'.format(uuid.uuid4())
    value = 'django-watchman-{}'.format(uuid.uuid4())

    cache = utils.get_cache(cache_name)

    cache.set(key, value)
    cache.get(key)
    cache.delete(key)
    return {cache_name: {"ok": True}} 
Example #24
Source File: tmp_storages.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def remove(self):
        default_storage.delete(self.get_full_path()) 
Example #25
Source File: tmp_storages.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def remove(self):
        cache.delete(self.name) 
Example #26
Source File: tmp_storages.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def open(self, mode='r'):
        if self.name:
            return open(self.get_full_path(), mode)
        else:
            tmp_file = tempfile.NamedTemporaryFile(delete=False)
            self.name = tmp_file.name
            return tmp_file 
Example #27
Source File: sendas2message.py    From django-pyas2 with GNU General Public License v3.0 5 votes vote down vote up
def add_arguments(self, parser):
        parser.add_argument("org_as2name", type=str)
        parser.add_argument("partner_as2name", type=str)
        parser.add_argument("path_to_payload", type=str)

        parser.add_argument(
            "--delete",
            action="store_true",
            dest="delete",
            default=False,
            help="Delete source file after processing",
        ) 
Example #28
Source File: test_attachment.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_thumbnails(self):
        for attachment in Attachment.objects.filter(instance=self.instance):
            url = image_url(attachment, 'small')
            filename = attachment.media_file.name.replace('.jpg', '')
            thumbnail = '%s-small.jpg' % filename
            self.assertNotEqual(
                url.find(thumbnail), -1)
            for size in ['small', 'medium', 'large']:
                thumbnail = '%s-%s.jpg' % (filename, size)
                self.assertTrue(
                    default_storage.exists(thumbnail))
                default_storage.delete(thumbnail) 
Example #29
Source File: forms.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def save(self, commit=True, *args, **kwargs):

        is_new = kwargs.pop('new')

        if is_new:
            photo = super(SiteForm, self).save(commit=False)
            photo.project_id = kwargs.pop('project_id')
            if 'region_id' in kwargs:
                photo.region_id = kwargs.pop('region_id')
            photo.save()

        photo = super(SiteForm, self).save()

        # if else for new  and update

        x = self.cleaned_data.get('x')
        y = self.cleaned_data.get('y')
        w = self.cleaned_data.get('width')
        h = self.cleaned_data.get('height')

        if x is not None and y is not None:
            image = Image.open(photo.logo)
            cropped_image = image.crop((x, y, w + x, h + y))
            resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
            # resized_image.save(photo.logo.path)
            resized_image_file = StringIO.StringIO()
            mime = mimetypes.guess_type(photo.logo.name)[0]
            plain_ext = mime.split('/')[1]
            resized_image.save(resized_image_file, plain_ext)
            default_storage.delete(photo.logo.name)
            default_storage.save(photo.logo.name, ContentFile(resized_image_file.getvalue()))
            resized_image_file.close()
        return photo 
Example #30
Source File: forms.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def save(self, commit=True, *args, **kwargs):
        is_new = kwargs.pop('new')
        
        if is_new:
            photo = super(ProjectForm, self).save(commit=False)
            photo.organization_id=kwargs.pop('organization_id')
            photo.save()
        
        photo = super(ProjectForm, self).save()

        x = self.cleaned_data.get('x')
        y = self.cleaned_data.get('y')
        w = self.cleaned_data.get('width')
        h = self.cleaned_data.get('height')

        if x is not None and y is not None:
            image = Image.open(photo.logo)
            cropped_image = image.crop((x, y, w+x, h+y))
            resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
            # resized_image.save(photo.logo.path)
            resized_image_file = StringIO.StringIO()
            mime = mimetypes.guess_type(photo.logo.name)[0]
            plain_ext = mime.split('/')[1]
            resized_image.save(resized_image_file, plain_ext)
            default_storage.delete(photo.logo.name)
            default_storage.save(photo.logo.name, ContentFile(resized_image_file.getvalue()))
            resized_image_file.close()
        return photo