Reputation: 129
I'm fairly new to Django and am having a bit of trouble trying to upload images
So broadly, I have a user class:
class User(AbstractBaseUser):
user_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
And a profile class:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
photo = models.ImageField(upload_to=<PATH>, blank=True, default=get_default_profile_image)
For the above PATH in profile, I tried to upload it to:
'profiles/' + user.user_id + '/image.png'
But if I try to do that, it says "AttributeError: 'OneToOneField' object has no attribute 'user_id'"
Is there any way to set the upload_to path as profiles/user_id/image.png where the user_id will be the unique id of that user?
Upvotes: 1
Views: 300
Reputation: 477676
You can pass a callable to the upload_to=…
parameter [Django-doc], so we can work with:
class Profile(models.Model):
def photo_upload(self, filename):
return f'profiles/{self.user.user_id}/{filename}'
user = models.OneToOneField(User, on_delete=models.CASCADE)
photo = models.ImageField(
upload_to=photo_upload,
blank=True,
default=get_default_profile_image
)
Upvotes: 2