Search code examples
djangosecurityrandomstatic-files

How to restrict static files to the user who uploaded them in Django?


From what I read, static files should be served directly by the server instead of using Python and Django. But I need to restrict access of files to the users who uploaded them. Unfortunately, the documentation doesn't have a section on serving static files uploaded by a user in production environments.

If I'm right, Facebook uses long urls that are hard to guess. This sounds like a reasonable approach to me. How can I automatically generate long ids and use them for uploaded media files in Django?


Solution

  • You can make use of slugify and datetime.

    from django.template.defaultfilters import slugify
    import datetime
    
    class MyModel(models.Model):
        title = models.CharField(max_length=150, db_index=True)
        image = models.Charfield(max_length=150, unique=True)
        ....
        ....
        def save(self):
            super(MyModel, self).save()
            date = datetime.date.today()
            self.image = '%i/%i/%i/%s' % (
                date.year, date.month, date.day, slugify(self.title)
            )
            super(MyModel, self).save()
    

    Or just

    Using time

    from time import time
    
    def get_upload_file_name(instance, filename):
        return "uploaded_files/%s_%s" %(str(time()).replace('.','_'), filename)
    
    class MyModel(models.Model):
        description = models.TextField()
        image = models.ImageField(upload_to=get_upload_file_name)
    
        def __unicode__(self):
            return "%s --> %s" % (self.user, self.description)
    

    Or

    By using this module - django-unique-random

    Hope it helps!