首页 > 解决方案 > How to prevent default image from being deleted when a user gets deleted?

问题描述

I have a model for users profile images and when I delete a user that has the default image, the default image also gets deleted. I believe this has to do because I set the on_delete=models.CASCADE.

I have tried to put on_delete=PROTECT in the ImageField but it doesn't recognize that attribute.

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

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'

def save(self, *args, **kwargs):
    super().save(*args, **kwargs)
    img = Image.open(self.image.path)
    if img.height > 300 or img.width > 300:
        output_size = (300,300)
        img.thumbnail(output_size)
        img.save(self.image.path)

标签: djangodjango-models

解决方案


on_delete=models.PROTECT是 of 的论点,models.ForeignKey其目的是用于关系。

在您的情况下,您需要的是通过扩展它并用您想要的功能覆盖原始类方法来创建自己的ImageField类类型。delete


推荐阅读