Answer the question
In order to leave comments, you need to log in
How to choose a random profile picture when registering?
I'm trying to make it so that when a user registers, a random photo is selected for his profile. I sketched mine
import random
from django.db import models
from django.conf import settings
class Profile(models.Model):
@staticmethod
def _get_random_photo():
photos_dir = (
settings.STATIC_ROOT / 'images' / 'default_profile_photos'
)
photo_paths = photos_dir.rglob('avatar*.png')
return random.choice(photo_paths)
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
date_of_birth = models.DateField(blank=True, null=True)
photo = models.ImageField(
upload_to='users/%Y/%m/%d',
blank=True,
default=_get_random_photo,
)
def __str__(self):
return f'Profile for user {self.user.username}'
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question