我使用ImageField存储用户的头像,这是我的模型:
class User(AbstractUser):
mugshot = models.ImageField(upload_to=user_mugshot_path)
def save(self, *args, **kwargs):
if not self.mugshot:
avatar = Avatar(rows=10, columns=10)
image_byte_array = avatar.get_image(string=self.username,
width=480,
height=480,
pad=10)
self.mugshot.save('default_mugshot.png', ContentFile(image_byte_array), save=False)
super().save(*args, **kwargs)
当用户注册时,这将为他/她创建默认的面部照片。预期的行为是当用户更新他们自己的照片时,默认的照片将被删除。所以我写了这样的表格和视图:
class MugshotForm(forms.ModelForm):
class Meta:
model = User
fields = ('mugshot',)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class MugshotChangeView(LoginRequiredMixin, UpdateView):
form_class = MugshotForm
template_name = 'users/mugshot_change.html'
success_url = '/users/profile'
def form_valid(self, form):
if form.has_changed():
self.object.mugshot.delete(save=False)
return super().form_valid(form)
# TODO: Can't update mugshot correctly
def get_object(self, queryset=None):
return self.request.user
但真正的行为是在更新照片时,旧的照片将被删除,但新照片与模特无关。它总是为用户创建一个新的默认照片。
代码有什么问题?谢谢你的帮助!