1

Hello, I am trying to pass the ID of a Model in an Image Field URL(upload_to) and then access it Through a URL unique to The instance.

Here's What I did (Amature);

class User(models.Model):
   serial = models.AutoField(primary_key=True)
   profile = models.ImageField(upload_to=f"profiles/{serial}/")

But all I'm Getting is OSError. I wanted to save the file to profiles/{serial}/ directory in the app. So Every Instance of the Model has its own Directory. And Then access it Through host:port/api/users/{serial}/profile.jpg My View Set is served through host:port/api/users

Is there a way I can Do it? Any Help is Highly Appreciated. A Detailed Explaination is Even more Appreciated.

Community
  • 1
  • 1
ax39T-Venom
  • 32
  • 1
  • 5

2 Answers2

0

From https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.FileField.upload_to

upload_to may also be a callable, such as a function. This will be called to obtain the upload path, including the filename. This callable must accept two arguments and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments are: instance and filename

So you can do something like this

def profile_handler(instance, file_name)
    return f"profiles/{instance.id}/{file_name}"

class User(models.Model):
   serial = models.AutoField(primary_key=True)
   profile = models.ImageField(upload_to=profile_handler)
Blackeagle52
  • 1,956
  • 17
  • 16
  • Here, ```instance.id``` is returning None so the URL becomes ```api/users/profiles/None```. Any Solutions ? – ax39T-Venom Apr 25 '20 at 13:19
  • 1
    Problem is that the instance isn't saved yet. Probably best to make your profile field nullable, save obj first, then set profile on obj. – Blackeagle52 Apr 25 '20 at 19:54
0

on model override save method like this

def save(self,*args, **kwargs):
    self.fieldname=currentmodel.objects.last().id+1
    super(Orders, self).save(*args, **kwargs)
Mr_sasani
  • 1
  • 4