在django上传时替换文件 [英] replacing a file while uploading in django

查看:202
本文介绍了在django上传时替换文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的models.py中有以下代码:

I have the following code in my models.py:

def upload_to_cars(instance, filename):
    blocks = filename.split('.')
    ext = blocks[-1]
    filename = "%s.%s" % (instance.name.replace(" ", "-"), ext)
    instance.title = blocks[0]
    return filename

class Cars(models.Model):
    image_file = models.ImageField(upload_to=upload_to_cars, null=True, blank=True)
    name = models.CharField(max_length=200)

当我上传第二张图像时,我想要第一个图像被删除。所以每个车课总是只有一个图像。相反,当我上传第二个文件时,django会在文件名的末尾添加一些字符。

When I upload a second image I want the first one to be deleted. So that there will always be only one image per car class. Instead, when I upload a second one, django adds some characters to the end of the filename.

我以为这个

filename = "%s.%s" %

旧图像将被替换?

任何建议?

谢谢!

编辑

感谢zxzak我做了,对我来说, ( os.remove(path)):

Thanks to zxzak I made it, for me it worked slightly different though (with os.remove(path) ):

    try:
        this = Company.objects.get(id=self.id)
        if this.image_file:
            os.remove(this.image_file.path)
    except ObjectDoesNotExist:
        pass


推荐答案

您可能需要覆盖保存方法来介绍这个行为。此代码将删除以前的image_field每次除了当一个汽车实例被创建。

You might want to override the save method in order to introduce this behaviour. This code will delete the previous image_field every time except when a Cars instance is being created.

from django.core.exceptions import ObjectDoesNotExist

class Cars(models.Model):
    image_file = models.ImageField(upload_to=upload_to_cars, null=True, blank=True)
    name = models.CharField(max_length=200)


    def save(self, *args, **kwargs):
        try:
            this = Cars.objects.get(id=self.id)
            if this.image_file:
                this.image_file.delete()   
        except ObjectDoesNotExist: 
            pass        
        super(Cars, self).save(*args, **kwargs)

这篇关于在django上传时替换文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆