oneat
oneat

Reputation: 10994

uploading file as id using models ind django

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?

Upvotes: 1

Views: 1079

Answers (1)

doniyor
doniyor

Reputation: 37846

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.

Upvotes: 1

Related Questions