9
9
95506682021-03-08 20:43:29
Django
9550668, 2021-03-08 20:43:29

Loading of image'ey through AbstractClass is impossible. Where is the mistake?

Good day to all. I have a problem and I can't find what it is.

The essence of the problem:
1. There was an article according to which the image loading class was written as avatars:
https://m.habr.com/en/post/505946/
Based on the article, there is a code:

import os
import uuid

from PIL import Image

from django.db import models

from utils.mixins import Uploader


def upload_to(instance, filename):
    """
    :param instance: instance of UsersAvatars
    :param filename: filename of the uploaded file by user
    :return: returns new url to upload
    """
    relative_path = instance.url_to_upload.rfind("media/") + len("media/")
    return instance.url_to_upload[relative_path:]


class AbstractBaseAvatar(models.Model):
    """
    Abstract Class for avatar user and avatar marathon
    """

    local_url = models.ImageField(upload_to=upload_to, null=True)
    url_to_upload = models.CharField(max_length=200, blank=True, null=True)

    @classmethod
    def upload_image(cls, image, owner_type, picture_type):
        image_name = cls.get_uuid_name_with_extension(image)
        avatar = cls.objects.create(
            local_url=image,
            url_to_upload=Uploader.get_path(owner_type, picture_type, image_name),
        )
        return avatar

    def delete(self, using=None, keep_parents=False):
        os.remove(self.url_to_upload)
        super().delete(using=using, keep_parents=keep_parents)

    @staticmethod
    def get_uuid_name_with_extension(image):
        img = Image.open(image)
        uuid_name = uuid.uuid4()
        return f"{uuid_name}.{img.format.lower()}"

    class Meta:
        abstract = True


2. Everything worked. The development went far ahead, but returned to the question and now when I upload the image I get an error: AttributeError: ' NoneType
' object has no attribute 'rfind'
Wrote (print(instance) in the upload_to function)
:
UserAvatar object (None)
class object is not passed.
Therefore, who can tell what is wrong? I must say right away that I would like not to change the principle already, because this class is inherited by the "darkness" of other classes and it will be necessary to rewrite a lot.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2021-03-08
@bacon

Debug the entire call chain, e.g. Uploader.get_path returns None

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question