0

thanks for any help in advanced. I am creating a personal website with Django, and I am coming from a Drupal background. I just started to learn the framework.

I am looking help with... a suggestion for a package or direction on how to get started on how to create a customizable file (image, video) path based off an user(Profile) name. So, a new directory would be created, when the user(Profile) is created, and the media for that user is stored in their directory. Then it would also get broken down into, if its a image or video with their own directory.

In theses files below, so far I have it setup like this.

settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'``

users/models.py

`class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    def __str__(self):
        return f'{self.user.username} Profile'`

Thanks.

I am new to the Django framework, and was hoping for some direction to point me in the right direction.

1 Answers1

0

Based on: Django dynamic FileField upload_to

import os

from django.db import models
from django.contrib.auth.models import User

def profile_upload_path(obj, filename):
    return os.path.join(obj.user.username, filename)

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to=profile_upload_path)

    def __str__(self):
        return f'{self.user.username} Profile'

I'm surprised how well this works! I was expecting a bunch of custom stuff and manually creating the dirs.. it sorta just does it all!

If you wanted to always have them the same name, this would also work:

def profile_upload_path(obj, filename):
    extension = filename[filename.rfind('.'):]
    return os.path.join(obj.user.username, f'profile{extension}')

I just pop'd off the extension so it doesn't end up malformed at the end.. so end result would be MEDIA_ROOT/{username}/profile{ext}, which might be good for organization

Nealium
  • 2,025
  • 1
  • 7
  • 9