"Could not derive file name from *" while uploading images in django

Viewed 750

I am building a image upload modle in django and the upload_to function to name the path. But it is showing me this error

from django.utils import timezone
from django.contrib.auth import get_user_model

# Create your models here.


def user_directory_path(instance, filename):
    return 'images/{0}/'.format(filename)


class Category(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name


class Images(models.Model):
    User = get_user_model()

    category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1)
    title = models.CharField(max_length=250)
    alt = models.TextField(null=True)
    image = models.ImageField(
        max_length=255,upload_to=user_directory_path, default='posts/default.jpg')
    slug = models.SlugField(max_length=250, unique_for_date='created')
    created = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(
        User, on_delete=models.PROTECT, related_name='author') ```   
3 Answers
def user_directory_path(instance, filename):
    return 'images/{0}/'.format(filename)

Here you're "converting" your filename into a directory name. If the uploaded file's name contains illegal characters you will get an error.

Try to not use the filename, or at least remove all the possible illegal characters from it before returning.

Notice that this function should return the path of a directory,not the path of a file, so you don't need the filename.

Found a solution that works

def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join('images/images', filename)

I believe you were recreating this one "Learn Django DRF - Building an Image API service - Django Rest Framework DRF - Part-1". I got it working just by deleting the first part of the return statement 'images/{0}/'. and it worked. But then it saved file directly in the media folder, not in media/images, so I figured out from the error message that I just should remove the last backslash from 'images/{0}/' after the closing curling brackets, like this 'images/{0}' and it is functioning like it should. Not sure if that's the right approach though.

Related