问题描述:文件:'AttributeError'对象没有属性'_committed'。重命名图像django模型。
答案: 在Django模型中,如果你想要重命名一个已经上传的图像文件,你需要进行以下步骤:
from django.db import models
class YourModel(models.Model):
old_image = models.ImageField(upload_to='images/')
new_image_path = models.CharField(max_length=255, blank=True)
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.core.files import File
import os
@receiver(pre_save, sender=YourModel)
def rename_image(sender, instance, **kwargs):
if instance.pk:
old_instance = YourModel.objects.get(pk=instance.pk)
if old_instance.old_image != instance.old_image:
# 删除旧的图像文件
if os.path.isfile(old_instance.old_image.path):
os.remove(old_instance.old_image.path)
# 重命名新的图像文件
new_image_path = 'new_images/' + instance.old_image.name
instance.new_image_path = new_image_path
instance.old_image.name = new_image_path
from django.shortcuts import render
from .forms import YourModelForm
def upload_image(request):
if request.method == 'POST':
form = YourModelForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
return render(request, 'success.html')
else:
form = YourModelForm()
return render(request, 'upload.html', {'form': form})
<img src="{{ your_model_instance.new_image_path }}" alt="New Image">
这样,你就可以在Django模型中重命名图像文件了。请注意,以上代码仅供参考,你需要根据你的实际需求进行适当的修改。
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云