django - 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)
解决方案
这 on_delete=models.PROTECT
是 of 的论点,models.ForeignKey
其目的是用于关系。
在您的情况下,您需要的是通过扩展它并用您想要的功能覆盖原始类方法来创建自己的ImageField
类类型。delete
推荐阅读
- sql - 为什么在 WHERE 子句中使用 NVL (Oracle)
- java - 为什么这个 apache camel rest 配置允许除 json 之外的其他媒体类型,即使配置为仅使用 jsons?
- amazon-web-services - 指向私有子网的弹性负载均衡器
- c# - ASP.NET WebForm 调用后面的代码的 onclick
- azure - 在 AKS 上使用带有 LetsEncrypt 和多个证书的证书管理器
- sql - 从已作为 HEX 数据导入 SQL 表的 CSV 文件读取
- c# - 如何在 ASP.NET 中向用户添加数据
- javascript - 循环中的axios请求
- ruby-on-rails - 使用 Capybara 测试文件上传 - 不是表单,而是按钮和 javascript 函数
- python - 将字符串解包成一/两个变量