'How to add username to the filefield?

I am making use of file fields in my model and I want it to be saved as username_field.jpeg (or whatever format it is in), for example for rent_agreement I want to store it as username_rent_agreement.jpg. How am I supposed to do it? Please Help. Thanks in advance.



Solution 1:[1]

You can specify that by passing a callable to the upload_to=... parameter [Django-doc]:

from django.db imports models
from django.contrib.auth import get_user_model

class SomeModel(models.Model):
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    rent_agreement = models.FileField(upload_to=rent_filename)

    def rent_filename(self, filename):
        return '{}_rent_agreement.jpg'.format(self.user.username)

In case such file already exists, it will add an underscore and a random sequence of characters at the end of the filename (before the extension).

You can retain the original extensions by obtaining that from the original filename:

from django.db imports models
from django.contrib.auth import get_user_model
from os.path import splitext

class SomeModel(models.Model):
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    rent_agreement = models.FileField(upload_to=rent_filename)

    def rent_filename(self, filename):
        __, ext = splitext(filename)
        return '{}_rent_agreement{}'.format(self.user.username, ext)

An extension however has strictly speaking no mapping on the format. A good system aims to inspect the file itself to determine that.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1