django.conf.settings.MEDIA_ROOT - python examples

Here are the examples of the python api django.conf.settings.MEDIA_ROOT taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

3 View Complete Implementation : helpers.py
Copyright GNU Affero General Public License v3.0
Author : liqd
def createThumbnail(imagefield):
    thumbnailer = get_thumbnailer(imagefield)
    thumbnail = thumbnailer.generate_thumbnail(
        {'size': (800, 400), 'crop': 'smart'})
    thumbnailer.save_thumbnail(thumbnail)
    thumbnail_path = os.path.join(settings.MEDIA_ROOT, thumbnail.path)
    return thumbnail_path

3 View Complete Implementation : utils.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
def save_media_file(output_file, file_content):
    #work around for Django bug where ContentFile does not support unicode
    outputfilename = path.join(settings.MEDIA_ROOT, output_file)
    f = open(outputfilename, "w")
    f.write(file_content)
    f.close()
    return outputfilename

3 View Complete Implementation : 0009_fix_image_upload.py
Copyright GNU General Public License v3.0
Author : bpepple
def fix_team_location(apps, schema_editor):
    Team = apps.get_model('comics', 'Team')
    for team in Team.objects.all():
        if (team.image):
            base_name = os.path.basename(team.image.name)
            img = 'images/teams/' + base_name
            old_path = settings.MEDIA_ROOT + '/' + str(team.image.name)
            new_path = settings.MEDIA_ROOT + '/' + img
            team.image = img
            team.save()
            # Move the file
            os.renames(old_path, new_path)

3 View Complete Implementation : comicimporter.py
Copyright GNU General Public License v3.0
Author : bpepple
    def create_images(self, db_obj, img_dir):
        base_name = os.path.basename(db_obj.image.name)
        old_image_path = settings.MEDIA_ROOT + '/images/' + base_name
        db_obj.image = utils.resize_images(db_obj.image, img_dir)
        db_obj.save()
        os.remove(old_image_path)

3 View Complete Implementation : test_topic_models.py
Copyright GNU Affero General Public License v3.0
Author : liqd
@pytest.mark.django_db
def test_image_deleted_after_update(topic_factory, ImagePNG):
    idea = topic_factory(image=ImagePNG)
    image_path = os.path.join(settings.MEDIA_ROOT, idea.image.path)
    thumbnail_path = createThumbnail(idea.image)

    astert os.path.isfile(image_path)
    astert os.path.isfile(thumbnail_path)

    idea.image = None
    idea.save()

    astert not os.path.isfile(image_path)
    astert not os.path.isfile(thumbnail_path)

3 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : cap-ntu
    def delete_all_related(self):
        # Delete all related objects
        # Bulk deletion to speed up
        with transaction.atomic():
            for frame in self.frames.all():
                frame.delete()
            for scene in self.scenes.all():
                scene.delete()
        self.dlmodels.clear()
        try_remove(str(self.statistics))
        try_remove(osp.join(settings.MEDIA_ROOT, str(self.audio_path)))
        try_remove(self.audio_json)
        try_remove(self.pkl_path)

3 View Complete Implementation : clear.py
Copyright MIT License
Author : ArnaudLevaufre
    def delete_folder(self, folder_name):
        print(f"Delete {folder_name} directory...")

        folder = os.path.join(settings.MEDIA_ROOT, folder_name)
        for the_file in os.listdir(folder):
            path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(path) and not the_file.startswith('.'):
                    os.unlink(path)
                    print(f"Delete file {path}")
                elif os.path.isdir(path):
                    shutil.rmtree(path)
                    print(f"Delete directory {path}")
            except Exception as e:
                print(f"Exception while deleting {path}: {e}")
                break

3 View Complete Implementation : version.py
Copyright GNU Affero General Public License v3.0
Author : 82Flex
@receiver(models.signals.post_delete, sender=Version)
def auto_delete_file_on_delete(sender, instance, **kwargs):
    """
    :type instance: Version
    """
    if instance.online_icon.name is not None:
        actual_path = os.path.join(settings.MEDIA_ROOT, instance.online_icon.name[1:])
        if os.path.isfile(actual_path):
            os.unlink(actual_path)
    if instance.storage.name is not None:
        actual_path = os.path.join(settings.MEDIA_ROOT, instance.storage.name[1:])
        if os.path.isfile(actual_path):
            os.unlink(actual_path)

3 View Complete Implementation : helpers.py
Copyright GNU Affero General Public License v3.0
Author : liqd
def createThumbnail(imagefield):
    thumbnailer = get_thumbnailer(imagefield)
    thumbnail = thumbnailer.generate_thumbnail(
        {'size': (800, 400), 'crop': 'smart'})
    thumbnailer.save_thumbnail(thumbnail)
    thumbnail_path = os.path.join(settings.MEDIA_ROOT, thumbnail.path)
    return thumbnail_path

3 View Complete Implementation : version.py
Copyright GNU Affero General Public License v3.0
Author : 82Flex
    def delete_model(self, request, obj):
        """
        :type obj: Version
        """
        abs_path = os.path.join(settings.MEDIA_ROOT, obj.storage.name)
        os.unlink(abs_path)
        super(VersionAdmin, self).delete_model(request, obj)

3 View Complete Implementation : test_dip_download.py
Copyright GNU Affero General Public License v3.0
Author : CCA-Public
    @patch("scope.views.zipfile.is_zipfile", return_value=True)
    def test_local_dip_download_zip_headers(self, mock_is_zipfile):
        # Make sure the MEDIA_ROOT directory exists
        os.makedirs(settings.MEDIA_ROOT, exist_ok=True)
        # Create temporay sized ZIP file for request
        path = os.path.join(settings.MEDIA_ROOT, "fake.zip")
        size = 1048575
        with _sized_tmp_file(path, size):
            url = reverse("download_dip", kwargs={"pk": self.local_dip.pk})
            response = self.client.get(url)
            self.astertEqual(response.status_code, 200)
            self.astertEqual(response["Content-Length"], str(size))
            self.astertEqual(response["Content-Type"], "application/zip")
            self.astertEqual(
                response["Content-Disposition"], 'attachment; filename="fake.zip"'
            )
            self.astertEqual(response["X-Accel-Redirect"], "/media/fake.zip")

3 View Complete Implementation : test_maptopic_models.py
Copyright GNU Affero General Public License v3.0
Author : liqd
@pytest.mark.django_db
def test_image_deleted_after_update(maptopic_factory, ImagePNG):
    idea = maptopic_factory(image=ImagePNG)
    image_path = os.path.join(settings.MEDIA_ROOT, idea.image.path)
    thumbnail_path = createThumbnail(idea.image)

    astert os.path.isfile(image_path)
    astert os.path.isfile(thumbnail_path)

    idea.image = None
    idea.save()

    astert not os.path.isfile(image_path)
    astert not os.path.isfile(thumbnail_path)

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : cap-ntu
    def get(self, request, pk):
        video = Video.objects.get(pk=pk)
        content = list()
        for frame in video.frames.all():
            with open(str(frame.json_path), "r") as f:
                content.append(json.load(f))

        # Write the json list to an entire json file
        table_name = str(video.video_file).split("/")[-1].split(".")[0] + ".json"
        table_path = os.path.join(settings.MEDIA_ROOT, "tables", table_name)
        with open(table_path, "w") as f:
            json.dump(content, f)
        video.table = table_path
        return Response({"time": time.time(), "data": "success"})

3 View Complete Implementation : test_idea_models.py
Copyright GNU Affero General Public License v3.0
Author : liqd
@pytest.mark.django_db
def test_image_deleted_after_update(idea_factory, ImagePNG):
    idea = idea_factory(image=ImagePNG)
    image_path = os.path.join(settings.MEDIA_ROOT, idea.image.path)
    thumbnail_path = createThumbnail(idea.image)

    astert os.path.isfile(image_path)
    astert os.path.isfile(thumbnail_path)

    idea.image = None
    idea.save()

    astert not os.path.isfile(image_path)
    astert not os.path.isfile(thumbnail_path)

3 View Complete Implementation : utils.py
Copyright Apache License 2.0
Author : edisonlz
def make_dirs(relative_path):
    if not relative_path:
        return
    absolute_path = os.path.join(settings.MEDIA_ROOT, relative_path)
    if os.path.isdir(absolute_path):
        return
    if absolute_path not in dirs_to_delete:
        dirs_to_delete.append(absolute_path)
    make_dirs(os.path.dirname(relative_path))
    os.mkdir(absolute_path)

3 View Complete Implementation : volumes.py
Copyright GNU General Public License v2.0
Author : guohongze
    def setUp(self):
        settings.MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
        self.driver = self.volume_clast()
        
        options = {
            'id' : 'test',
            'tmpPath' : self.driver._join_path(os.path.dirname(__file__), 'tmbtest'),
            'tmbURL' : 'http://example.com/files', #test _urlize
            'tmbSize' : 32
        }

        self.driver.mount(options)
        self.default_path = self.driver.default_path()
        self.realPath = self.driver.decode(self.default_path)

3 View Complete Implementation : 0009_fix_image_upload.py
Copyright GNU General Public License v3.0
Author : bpepple
def fix_character_location(apps, schema_editor):
    Character = apps.get_model('comics', 'Character')
    for character in Character.objects.all():
        if (character.image):
            base_name = os.path.basename(character.image.name)
            img = 'images/characters/' + base_name
            old_path = settings.MEDIA_ROOT + '/' + str(character.image.name)
            new_path = settings.MEDIA_ROOT + '/' + img
            character.image = img
            character.save()
            # Move the file
            os.rename(old_path, new_path)

3 View Complete Implementation : file_storage.py
Copyright GNU Affero General Public License v3.0
Author : TheSpaghettiDetective
def _save_to_file_system(dest_path, file_obj, container, return_url):
    fqp = path.join(settings.MEDIA_ROOT, container, dest_path)
    if not path.exists(path.dirname(fqp)):
        os.makedirs(path.dirname(fqp))

    with open(fqp, 'wb+') as dest_file:
        copyfileobj(file_obj, dest_file)

    if not return_url:
        return

    uri = '{}{}/{}'.format(settings.MEDIA_URL, container, dest_path)
    return settings.INTERNAL_MEDIA_HOST + uri, site.build_full_url(uri)

3 View Complete Implementation : fields.py
Copyright Apache License 2.0
Author : edisonlz
    def test_thumbnail(self):
        model = TestThumbnailFieldModel(photo=RELATIVE_PIC_NAME)
        thumb = model.photo.thumbnail
        tag = model.photo.thumbnail_tag
        base_name = RELATIVE_PIC_NAME.replace('.', '_')
        expected_filename = os.path.join(settings.MEDIA_ROOT,
                                         '%s_50x50_q85.jpg' % base_name)
        self.verify_thumbnail((50, 37), thumb, expected_filename)
        expected_tag = ('<img src="%s" width="50" height="37" alt="" />' %
                        '/'.join([settings.MEDIA_URL.rstrip('/'),
                                  '%s_50x50_q85.jpg' % base_name]))
        self.astertEqual(tag, expected_tag)

3 View Complete Implementation : models.py
Copyright MIT License
Author : djangocon
def twitter_card_path(instance, __):

    relative_path = 'pretalx_utils/twitter_card_{}.png'.format(instance.submission.code)

    # Delete any existing image
    fullname = os.path.join(settings.MEDIA_ROOT, relative_path)

    container_dir = os.path.dirname(fullname)

    if not os.path.exists(container_dir):
        os.makedirs(container_dir)

    if os.path.exists(fullname):
        os.remove(fullname)
    return relative_path

3 View Complete Implementation : 0009_fix_image_upload.py
Copyright GNU General Public License v3.0
Author : bpepple
def fix_arc_location(apps, schema_editor):
    Arc = apps.get_model('comics', 'Arc')
    for arc in Arc.objects.all():
        if (arc.image):
            base_name = os.path.basename(arc.image.name)
            img = 'images/arcs/' + base_name
            old_path = settings.MEDIA_ROOT + '/' + str(arc.image.name)
            new_path = settings.MEDIA_ROOT + '/' + img
            arc.image = img
            arc.save()
            # Move the file
            os.rename(old_path, new_path)

3 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : Palanaeum
    def save_uploaded_file(self, uploaded_file: UploadedFile):
        save_path = pathlib.Path(settings.MEDIA_ROOT, 'sources', str(self.event_id), uploaded_file.name)
        if save_path.exists():
            save_path = save_path.with_name("{}_{}{}".format(save_path.name, time.time(), save_path.suffix))

        save_path.parent.mkdir(parents=True, exist_ok=True, mode=0o775)
        with open(str(save_path), mode='wb') as save_file:
            for chunk in uploaded_file.chunks():
                save_file.write(chunk)

        self.file = str(save_path.relative_to(settings.MEDIA_ROOT))
        return

3 View Complete Implementation : classes.py
Copyright Apache License 2.0
Author : edisonlz
    def testRGBA(self):
        # RGBA image
        rgba_pic_name = os.path.join(settings.MEDIA_ROOT,
                                     'sorl-thumbnail-test_rgba_source.png')
        Image.new('RGBA', PIC_SIZE).save(rgba_pic_name)
        self.images_to_delete.add(rgba_pic_name)
        # Create thumb and verify it's still RGBA
        rgba_thumb_name = os.path.join(settings.MEDIA_ROOT,
                                       'sorl-thumbnail-test_rgba_dest.png')
        thumb = Thumbnail(source=rgba_pic_name, dest=rgba_thumb_name,
                          requested_size=(240, 240))
        self.verify_thumbnail((240, 180), thumb, expected_mode='RGBA')

3 View Complete Implementation : test_idea_models.py
Copyright GNU Affero General Public License v3.0
Author : liqd
@pytest.mark.django_db
def test_image_deleted_after_update(idea_factory, ImagePNG):
    idea = idea_factory(image=ImagePNG)
    image_path = os.path.join(settings.MEDIA_ROOT, idea.image.path)
    thumbnail_path = createThumbnail(idea.image)

    astert os.path.isfile(image_path)
    astert os.path.isfile(thumbnail_path)

    idea.image = None
    idea.save()

    astert not os.path.isfile(image_path)
    astert not os.path.isfile(thumbnail_path)

3 View Complete Implementation : section.py
Copyright GNU Affero General Public License v3.0
Author : 82Flex
@receiver(models.signals.post_delete, sender=Section)
def auto_delete_file_on_delete(sender, instance, **kwargs):
    """
    :type instance: Section
    """
    if instance.icon.name is not None:
        actual_path = os.path.join(settings.MEDIA_ROOT, instance.icon.name[1:])
        if os.path.isfile(actual_path):
            os.unlink(actual_path)

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : timothyryanwalsh
def download_dfxml(request, pk):
    # Generate reports and wait for result
    file_path = os.path.join(settings.MEDIA_ROOT,
                             'dfxml',
                             '{}_dfxml.xml'.format(str(pk)))
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="text/xml")
            response['Content-Disposition'] = 'inline; filename={}'.format(os.path.basename(file_path))
            return response

3 View Complete Implementation : processing.py
Copyright Apache License 2.0
Author : cap-ntu
def audio_postproc(video, audio_response, fr):
    # Save audio response
    filename = str(video.video_file).split('/')[-1].split('.')[0] + "_audio.json"
    path = osp.join(settings.MEDIA_ROOT, "json", filename)
    with open(path, "w") as fw:
        json.dump(audio_response, fw)
    video.audio_json = path
    video.fr = fr
    return

3 View Complete Implementation : device_type.py
Copyright GNU Affero General Public License v3.0
Author : 82Flex
@receiver(models.signals.post_delete, sender=DeviceType)
def auto_delete_file_on_delete(sender, instance, **kwargs):
    """
    :type instance: DeviceType
    """
    if instance.icon.name is not None:
        actual_path = os.path.join(settings.MEDIA_ROOT, instance.icon.name[1:])
        if os.path.isfile(actual_path):
            os.unlink(actual_path)

3 View Complete Implementation : test_tasks.py
Copyright GNU Affero General Public License v3.0
Author : CCA-Public
    @patch("scope.tasks.tarfile.open", return_value=MagicMock())
    @patch("scope.tasks.tarfile.is_tarfile", return_value=True)
    def test_extract_mets_found_in_tar(self, mock_is_tarfile, mock_tarfile_open):
        mock_member = Mock()
        mock_member.name = "relative/path/METS.ab028cb0-9942-4f26-a966-7197d7a2e15a.xml"
        mock_tarfile = Mock()
        mock_tarfile.getmembers.return_value = [mock_member]
        mock_tarfile_open().__enter__.return_value = mock_tarfile
        mets_path = extract_mets("/DIP.tar")
        self.astertEqual(
            os.path.join(
                settings.MEDIA_ROOT, "METS.ab028cb0-9942-4f26-a966-7197d7a2e15a.xml"
            ),
            mets_path,
        )

3 View Complete Implementation : classes.py
Copyright Apache License 2.0
Author : edisonlz
    def setUp(self):
        super(DjangoThumbnailTest, self).setUp()
        # Add another source image in a sub-directory for testing subdir and
        # basedir.
        self.sub_dir = os.path.join(settings.MEDIA_ROOT, 'test_thumbnail')
        try:
            os.mkdir(self.sub_dir)
        except OSError:
            past
        self.pic_subdir = os.path.join(self.sub_dir, RELATIVE_PIC_NAME)
        Image.new('RGB', PIC_SIZE).save(self.pic_subdir, 'JPEG')
        self.images_to_delete.add(self.pic_subdir)

3 View Complete Implementation : views.py
Copyright MIT License
Author : MateLabs
@csrf_exempt
def get_treated_data(request):
    page_no = int(request.GET.get("page_num", 1))
    experiment_id = int(request.GET.get("experiment_id"))
    print("Page no:", page_no)

    if experiment_id is None:
        return JsonResponse({"status": "failure", "message": "Experiment id is file"})

    experiment = Experiment.objects.get(pk=experiment_id)
    treated_file_name = experiment.treated_file_path

    dataset_path = os.path.join(settings.MEDIA_ROOT, treated_file_name)
    filename, file_extension = os.path.splitext(dataset_path)

    df = DataLoader.load(dataset_path)
    # df = pd.read_csv(dataset_path)
    df = df.iloc[(page_no - 1) * 20:(page_no - 1) * 20 + 20, :]
    return JsonResponse(df.to_json(orient='records'), safe=False)

3 View Complete Implementation : processing.py
Copyright Apache License 2.0
Author : cap-ntu
def audio_process(video, video_path, models_to_apply):
    audio_name = str(video.video_file).split("/")[-1].split(".")[0] + ".wav"
    audio_path = osp.join("audios", audio_name)
    video.audio_path = audio_path
    abs_audio_path = osp.join(settings.MEDIA_ROOT, audio_path)
    # Extract wav file
    audio_decode(video_path, abs_audio_path)
    # rpc call
    print("Processing wav file through rpc call...")
    with RpcClient(port="50052") as rpc_client:
        audio_response, fr = rpc_client.service_request(abs_audio_path.encode(), models_to_apply)
        audio_response = json.loads(audio_response)
        fr = int(fr)
    # Save audio result
    audio_postproc(video, audio_response, fr)
    return audio_response

3 View Complete Implementation : test_models.py
Copyright GNU Affero General Public License v3.0
Author : liqd
@pytest.mark.django_db
def test_image_deleted_after_update(user_factory, ImagePNG):
    user = user_factory(_avatar=ImagePNG)
    image_path = os.path.join(settings.MEDIA_ROOT, user._avatar.path)
    thumbnail_path = helpers.createThumbnail(user._avatar)

    astert os.path.isfile(image_path)
    astert os.path.isfile(thumbnail_path)

    user._avatar = None
    user.save()

    astert not os.path.isfile(image_path)
    astert not os.path.isfile(thumbnail_path)

3 View Complete Implementation : classes.py
Copyright Apache License 2.0
Author : edisonlz
    def testAlternateExtension(self):
        basename = RELATIVE_PIC_NAME.replace('.', '_')
        # Control JPG
        thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME,
                                requested_size=(240, 120))
        expected = os.path.join(settings.MEDIA_ROOT, basename)
        expected += '_240x120_q85.jpg'
        expected_jpg = expected
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
        # Test PNG
        thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME,
                                requested_size=(240, 120), extension='png')
        expected = os.path.join(settings.MEDIA_ROOT, basename)
        expected += '_240x120_q85.png'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
        # Compare the file size to make sure it's not just saving as a JPG with
        # a different extension.
        self.astertNotEqual(os.path.getsize(expected_jpg),
                            os.path.getsize(expected))

3 View Complete Implementation : account.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
    @property
    def profile_image_url(self):
        """ Return placeholder profile image if user didn't upload one"""

        if self.profile_image:
            file_exists = default_storage.exists(
                os.path.join(settings.MEDIA_ROOT, self.profile_image.name)
            )
            if file_exists:
                return self.profile_image.url

        return "/static/img/no_image_md.png"

3 View Complete Implementation : 0009_fix_image_upload.py
Copyright GNU General Public License v3.0
Author : bpepple
def fix_publisher_location(apps, schema_editor):
    Publisher = apps.get_model('comics', 'Publisher')
    for publisher in Publisher.objects.all():
        if (publisher.logo):
            base_name = os.path.basename(publisher.logo.name)
            img = 'images/publishers/' + base_name
            old_path = settings.MEDIA_ROOT + '/' + str(publisher.logo.name)
            new_path = settings.MEDIA_ROOT + '/' + img
            publisher.logo = img
            publisher.save()
            # Move the file
            os.renames(old_path, new_path)

3 View Complete Implementation : utils.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
def save_media_file(output_file, file_content):
    #work around for Django bug where ContentFile does not support unicode
    outputfilename = path.join(settings.MEDIA_ROOT, output_file)
    f = open(outputfilename, "w")
    f.write(file_content)
    f.close()
    return outputfilename

3 View Complete Implementation : storage.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, location=None, base_url=None):
        if location is None:
            location = settings.MEDIA_ROOT
        self.base_location = location
        self.location = abspathu(self.base_location)
        if base_url is None:
            base_url = settings.MEDIA_URL
        self.base_url = base_url

3 View Complete Implementation : account.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
    @property
    def profile_image_thumb_url(self):
        """ Return placeholder profile image if user didn't upload one"""

        if self.profile_image_thumb:
            file_exists = default_storage.exists(
                os.path.join(settings.MEDIA_ROOT, self.profile_image_thumb.name)
            )
            if file_exists:
                return self.profile_image_thumb.url

        return "/static/img/no_image_md.png"

3 View Complete Implementation : 0009_fix_image_upload.py
Copyright GNU General Public License v3.0
Author : bpepple
def fix_creator_location(apps, schema_editor):
    Creator = apps.get_model('comics', 'Creator')
    for creator in Creator.objects.all():
        if (creator.image):
            base_name = os.path.basename(creator.image.name)
            img = 'images/creators/' + base_name
            old_path = settings.MEDIA_ROOT + '/' + str(creator.image.name)
            new_path = settings.MEDIA_ROOT + '/' + img
            creator.image = img
            creator.save()
            # Move the file
            os.renames(old_path, new_path)

3 View Complete Implementation : volumes.py
Copyright GNU General Public License v2.0
Author : guohongze
    def test_options(self):
        
        options = self.driver.options(self.default_path)
        self.astertEqual(options['tmbUrl'], 'http://example.com/files/')
        self.astertEqual(options['separator'], os.sep)
        self.astertEqual(options['path'].startswith(settings.MEDIA_ROOT), False)
        self.astertIn('url', options)
        self.astertIn('archivers', options)
        self.astertIn('disabled', options)
        self.astertIn('copyOverwrite', options)

3 View Complete Implementation : classes.py
Copyright Apache License 2.0
Author : edisonlz
    def testUnicodeName(self):
        unicode_name = 'sorl-thumbnail-ążśź_source.jpg'
        unicode_path = os.path.join(settings.MEDIA_ROOT, unicode_name)
        Image.new('RGB', PIC_SIZE).save(unicode_path)
        self.images_to_delete.add(unicode_path)
        thumb = DjangoThumbnail(relative_source=unicode_name,
                                requested_size=(240, 120))
        base_name = unicode_name.replace('.', '_')
        expected = os.path.join(settings.MEDIA_ROOT,
                                base_name + '_240x120_q85.jpg')
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)

3 View Complete Implementation : test_tasks.py
Copyright GNU Affero General Public License v3.0
Author : CCA-Public
    @patch("elasticsearch_dsl.DocType.save")
    def setUp(self, mock_es_save):
        self.ss_uuid = "a2cddc10-6132-4690-8dd9-25ee7a01943f"
        self.mets_path = os.path.join(settings.MEDIA_ROOT, "METS.%s.xml" % self.ss_uuid)
        self.dip = DIP.objects.create(
            ss_uuid=self.ss_uuid, ss_host_url="http://192.168.1.128:62081"
        )
        DigitalFile.objects.create(uuid="fake-uuid", dip=self.dip, size_bytes=1)

3 View Complete Implementation : 0009_fix_image_upload.py
Copyright GNU General Public License v3.0
Author : bpepple
def fix_issue_location(apps, schema_editor):
    Issue = apps.get_model('comics', 'Issue')
    for issue in Issue.objects.all():
        if (issue.cover):
            base_name = os.path.basename(issue.cover.name)
            img = 'images/issues/' + base_name
            old_path = settings.MEDIA_ROOT + '/' + str(issue.cover.name)
            new_path = settings.MEDIA_ROOT + '/' + img
            issue.cover = img
            issue.save()
            # Move the file
            os.renames(old_path, new_path)

3 View Complete Implementation : release.py
Copyright GNU Affero General Public License v3.0
Author : 82Flex
@receiver(models.signals.post_delete, sender=Release)
def auto_delete_file_on_delete(sender, instance, **kwargs):
    """
    :type instance: Release
    """
    if instance.icon.name is not None:
        actual_path = os.path.join(settings.MEDIA_ROOT, instance.icon.name[1:])
        if os.path.isfile(actual_path):
            os.unlink(actual_path)

3 View Complete Implementation : fields.py
Copyright Apache License 2.0
Author : edisonlz
    def test_extension(self):
        model = TestThumbnailFieldExtensionModel(photo=RELATIVE_PIC_NAME)
        thumb = model.photo.thumbnail
        tag = model.photo.thumbnail_tag
        expected_filename = os.path.join(settings.MEDIA_ROOT,
            'sorl-thumbnail-test_source_jpg_50x50_q85.png')
        self.verify_thumbnail((50, 37), thumb, expected_filename)
        expected_tag = '<img src="%s" width="50" height="37" alt="" />' % \
            '/'.join((settings.MEDIA_URL.rstrip('/'),
                      'sorl-thumbnail-test_source_jpg_50x50_q85.png'))
        self.astertEqual(tag, expected_tag)

3 View Complete Implementation : fields.py
Copyright Apache License 2.0
Author : edisonlz
    def test_extra_thumbnails(self):
        model = TestThumbnailFieldModel(photo=RELATIVE_PIC_NAME)
        self.astertTrue('admin' in model.photo.extra_thumbnails)
        thumb = model.photo.extra_thumbnails['admin']
        tag = model.photo.extra_thumbnails_tag['admin']
        expected_filename = os.path.join(settings.MEDIA_ROOT,
            'sorl-thumbnail-test_source_jpg_30x30_crop_q85.jpg')
        self.verify_thumbnail((30, 30), thumb, expected_filename)
        expected_tag = '<img src="%s" width="30" height="30" alt="" />' % \
            '/'.join((settings.MEDIA_URL.rstrip('/'),
                      'sorl-thumbnail-test_source_jpg_30x30_crop_q85.jpg'))
        self.astertEqual(tag, expected_tag)

3 View Complete Implementation : os_version.py
Copyright GNU Affero General Public License v3.0
Author : 82Flex
@receiver(models.signals.post_delete, sender=OSVersion)
def auto_delete_file_on_delete(sender, instance, **kwargs):
    """
    :type instance: OSVersion
    """
    if instance.icon.name is not None:
        actual_path = os.path.join(settings.MEDIA_ROOT, instance.icon.name[1:])
        if os.path.isfile(actual_path):
            os.unlink(actual_path)

3 View Complete Implementation : admin_views.py
Copyright GNU Affero General Public License v3.0
Author : Palanaeum
@user_pastes_test(lambda u: u.is_superuser, login_url="auth_login")
def index(request):
    usage = shutil.disk_usage(settings.MEDIA_ROOT)
    total_space_str = "{:.2f} Gb".format(usage.total / 1024**3)
    used_space_str = "{:.2f} Gb".format(usage.used / 1024**3)
    free_space_str = "{:.2f} Gb".format(usage.free / 1024**3)
    return render(request, 'palanaeum/admin/admin_index.html',
                  {'used_space': usage.used, 'available_space': usage.free,
                   'total_space': usage.total, 'total_space_str': total_space_str,
                   'free_space_str': free_space_str, 'used_space_str': used_space_str})

0 View Complete Implementation : fields.py
Copyright Apache License 2.0
Author : edisonlz
    def test_generate_on_save(self):
        main_thumb = os.path.join(settings.MEDIA_ROOT, 'test',
                        'sorl-thumbnail-test_source_jpg_50x50_q85.jpg')
        admin_thumb = os.path.join(settings.MEDIA_ROOT, 'test',
                        'sorl-thumbnail-test_source_jpg_30x30_crop_q85.jpg')
        self.images_to_delete.add(main_thumb)
        self.images_to_delete.add(admin_thumb)
        # Default setting is to only generate when the thumbnail is used.
        model = TestThumbnailFieldModel()
        source = ContentFile(open(PIC_NAME).read())
        model.photo.save(RELATIVE_PIC_NAME, source, save=False)
        self.images_to_delete.add(model.photo.path)
        self.astertFalse(os.path.exists(main_thumb))
        self.astertFalse(os.path.exists(admin_thumb))
        os.remove(model.photo.path)
        # But it's easy to set it up the other way...
        model = TestThumbnailFieldGenerateModel()
        source = ContentFile(open(PIC_NAME).read())
        model.photo.save(RELATIVE_PIC_NAME, source, save=False)
        self.astert_(os.path.exists(main_thumb))
        self.astert_(os.path.exists(admin_thumb))