Django 重写 Profile.save 压缩图片后新用户未自动创建 Profile
新建用户时,post_save 信号会执行:
Profile.objects.create(user=instance)
由于 Profile.image 设置了默认值:
image = models.ImageField(default='default.jpg', upload_to='profile_pic')
新创建的 Profile 并没有上传图片,因此 self.image.name 的值是 default.jpg。
但重写后的 save() 方法在执行完 super().save() 后,会无条件打开图片:
img = Image.open(self.image.path)
这时程序会去媒体目录中查找 default.jpg。如果该文件不存在、路径不正确、没有读取权限,或图片本身无法被 Pillow 处理,就会抛出异常。异常发生在 post_save 信号中,导致 Profile 创建过程中断;如果该操作处于事务中,已经写入的 Profile 记录也会回滚。因此最终出现:
RelatedObjectDoesNotExist at /login/ User has no profile
另外,当前两个信号接收器还会在新建用户时连续保存两次 Profile:create_profile 创建一次,save_profile 又通过 instance.profile.save() 保存一次,使图片处理逻辑被重复执行。
1. 跳过默认图片
只有用户实际上传了图片时才进行压缩,不处理 default.jpg:
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_pic') def __str__(self): return f'{self.user}\'s Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.image.name == 'default.jpg': return 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)
同时应确保媒体目录中确实存在 default.jpg,但即使存在,也不应该在每次创建用户时去处理或覆盖这个共享的默认图片。
2. 合并信号,避免重复保存
可以将两个信号接收器合并为一个:
from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def manage_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance)
如果确实需要在更新 User 时同时保存 Profile,可以写成:
@receiver(post_save, sender=User) def manage_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) else: instance.profile.save()
3. 为已存在但缺少 Profile 的用户补建数据
修复代码后,之前创建失败的用户仍然没有对应 Profile。可以在 Django shell 中补建:
python manage.py shell
然后执行:
from django.contrib.auth.models import User from users.models import Profile for user in User.objects.filter(profile__isnull=True): Profile.objects.create(user=user)
核心修复点就是:不要在 Profile.save() 中无条件打开并处理默认图片,只处理用户实际上传的图片。
内容的提问来源于stack exchange,提问作者Bs Joy

