M
M
mkone1122020-12-16 00:56:43
Django
mkone112, 2020-12-16 00:56:43

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

a bike:
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}'

But it looks bad, for example, it violates the Django convention for placing custom methods at the end of the model. Please let me know how to do/do this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mkone112, 2021-02-28
@mkone112

Answer in another question

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question