1

I have short model definition

class File(models.Model):
    id = models.IntegerField(primary_key=True);
    file = models.FileField(upload_to='%id')
    title = models.CharField(max_length=128)
    upload_date = models.DateTimeField(auto_now_add=True, blank=True);

as u see (or not) I would like this model to handle upload so file name would be the same as row id. Is it possible to do it this way somehow?

oneat
  • 10,778
  • 16
  • 52
  • 70
  • Model itself will not upload anything for you, you still need the client side form to upload and a Django View to handle the request. – dmitryro Jun 28 '16 at 02:07
  • It is all done, but I am thinking if by changing upload_to I can achieve change in name of file into id. - I just put data from form to model as the easiest way. – oneat Jun 28 '16 at 02:31
  • So you have file = request.files['file'] and then file.filename into your char field – dmitryro Jun 28 '16 at 02:54
  • Possible duplicate of [In django changing the file name of an uploaded file](http://stackoverflow.com/questions/2680391/in-django-changing-the-file-name-of-an-uploaded-file) – solarissmoke Jun 28 '16 at 03:04

1 Answers1

1

sure you can

def update_filename(instance, filename):
    filename_ = instance.id
    file_extension = filename.split('.')[-1]
    return '%s.%s' % (filename_, file_extension)

class File(models.Model):
    id = models.IntegerField(primary_key=True)
    file = models.FileField(upload_to=update_filename)
    title = models.CharField(max_length=128)
    upload_date = models.DateTimeField(auto_now_add=True, blank=True)

and I would change the class name to something else, so it does not shadow the built in File.

doniyor
  • 36,596
  • 57
  • 175
  • 260