0

I use Django 2.x. I try to upload the file "image.png".

models.py:

def file_name(instance, filename):
    return os.path.join('uploads', 'my_name.png')

class FileForm(models.Model):
    file = models.FileField(upload_to=file_name, null=True)

As a result image.png is uploads into "uploads" folder with new filename "my_name.png" (..uploads/my_name.png)

But when I do this: (I just take os.path.join('uploads', 'my_name.png') and put instead file_name)

class FileForm(models.Model):
        file = models.FileField(upload_to=os.path.join('uploads', 'my_name.png'), null=True)

The result is image.png is just uploaded into "uploads/my_name.png" folder (...uploads/my_name.png/image.png)

Why is this happening?

Valery
  • 321
  • 1
  • 13
  • Because you need a callable. What you have done in the first one is right, except you need to use `filename` instead of `'my_name.png'`. – Daniel Roseman Jun 24 '18 at 15:27
  • Thank you. I specially wrote "my_name.png" to find out how it works. What do you mean "callable", sorry I'm new here. I thought I can put result of this function into FileField and result will be the same – Valery Jun 24 '18 at 15:39
  • @Valery You can check what is callable in this [SO answer](https://stackoverflow.com/a/111255/4436641). `upload_to` expects a string of the directory, if you use a callable in the upload_to, it will be the absolute file path including the filename. So in your case, `upload_to=os.path.join('uploads', 'my_name.png')` will set the upload directory to `uploads/my_name.png/`. You can see it more in this [link](https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.FileField.upload_to). – Rieljun Liguid Jun 24 '18 at 15:56
  • @Rieljun Liguid Oh thank you so much! I completely understand this. Also I find the the condition in **file.py**: `def generate_filename(self, instance, filename): if callable(self.upload_to): filename = self.upload_to(instance, filename)` – Valery Jun 24 '18 at 16:02

0 Answers0