简体   繁体   English

如何防止每次用户提交自定义UserChangeForm时Django保存图像?

[英]How do I prevent Django from saving an Image each time a user submits a custom UserChangeForm?

So, I'm a newb in Django and I've defined a custom user, users are allowed to update their profiles using a ModelForm however each time I submit the form it uploads and proceses the thumbnail again, how can I check if the upload field has changed and exclude it from the submission if it has not? 因此,我是Django的新手,我定义了一个自定义用户,允许用户使用ModelForm更新其个人资料,但是每次我提交表单上传并再次处理缩略图时,如何检查上传内容字段已更改,如果没有,则将其从提交中排除?

here is my code: 这是我的代码:

views.py views.py

@login_required
def account_edit(request):
    u = AccountUser.objects.get(pk=request.user.id)
    if request.method == 'POST':
        form = UserChangeForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
    else:
        form = UserChangeForm(instance=request.user)
    return render_to_response('accounts/account.html', locals(), RequestContext(request))

models.py models.py

class AccountUser(AbstractUser):
    about = models.TextField(blank=True, null=True)
    occupation = models.CharField(max_length=255, blank=True, null=True)
    avatar = models.ImageField(upload_to="accounts/avatars", blank=True, null=True)
    slug = models.SlugField(default='', blank=True)
    following = models.ManyToManyField('AccountUser', related_name="followed_by", blank=True, null=True)
    thumbnail = models.ImageField(upload_to="accounts/avatars/thumbnails", blank=True, null=True)

    def save(self, *args, **kwargs):
        if self.avatar is not None:
            img = Image.open(self.avatar.file)
            thumbnail = ImageOps.fit(img, (220, 220,), method=Image.ANTIALIAS)


            temp_handle_img = StringIO()
            img.save(temp_handle_img, 'png')
            temp_handle_img.seek(0)

            temp_handle_thumbnail = StringIO()
            thumbnail.save(temp_handle_thumbnail, 'png')
            temp_handle_thumbnail.seek(0)

            suf_thumbnail = SimpleUploadedFile(os.path.split(self.avatar.name[-1],temp_handle_thumbnail.read(), content_type='image/png')
            fname_thumbnail = "%s.png" % os.path.splitext(self.avatar.name)[0]

            sufImg = SimpleUploadedFile(os.path.split(self.avatar.name)[-1], temp_handle_img.read(), content_type='image/png')
            fnameImg = "%s.png" % os.path.splitext(self.avatar.name)[0]

            self.thumbnail.save(fname_thumbnail, suf_thumbnail, save=False)
            self.avatar.save(fnameImg, sufImg, save=False)
        if not self.slug:
            self.slug = slugify(self.username)
        super(AccountUser, self).save(*args, **kwargs)

You should remove 'thumbnail' from your model fields and set it as a def . 您应该从模型字段中删除“缩略图”并将其设置为def thumbnail doesn't seem to need to be in db. 缩略图似乎不需要在数据库中。

Edit: 编辑:

I think, you should hash your picture for see if changed. 我认为,您应该对图片进行哈希处理以查看是否已更改。 Use hashlib.md5 for example. 例如,使用hashlib.md5

def save(self, *args, **kwargs):
    if self.avatar is not None:
        # Do your stuff
        cur_file = AccountUser.objects.get(pk=self.pk).avatar.file
        cur_file_hash = md5(cure_file.read()).hexdigest()
        new_file_hash = md5(temp_handle_img.read()).hexdigest()
        if cur_file_hash != new_file_hash:
            # Do some stuff

I don't think I exactly resolve it, but it should give you a way... 我认为我无法完全解决它,但是它应该给您一种方法...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django中的自定义UserChangeForm - Custom UserChangeForm in Django 如何在自定义UserChangeForm中覆盖用户名的django'unique'错误消息 - How to override django 'unique' error message for username in custom UserChangeForm 如何在 Django 的 UserChangeForm 中更新 ManytoManyField? - How to update ManytoManyField in UserChangeForm in Django? 如何从Django userchangeform中的登录页面删除用户名字段 - how to remove username field from login page in django userchangeform 防止Django imageField上传/保存图像 - Prevent Django imageField from uploading / saving image 如何将提交ModelForm的用户的信息传递给ManyToMany保存? - How do I pass information from the user that submits a ModelForm to a ManyToMany save? 如何防止用户移动图像(他们可以使用箭头或 WASD 键移动图像)离开 canvas? - How do I prevent the user from moving image (they can move the image with the arrow or WASD keys) off of the canvas? Python-每次用户提交表单时都写入多个JSON文件 - Python - Write multiple JSON files each time user submits the form 在Django中覆盖UserChangeForm - Overriding UserChangeForm in django 如何在Django中为每个用户附加一个不同的数据库? - How do I attach a different database to each user in Django?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM