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

Time:10-20

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') ```   

CodePudding user response:

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.

CodePudding user response:

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)
  • Related