【发布时间】:2023-01-13 06:00:41
【问题描述】:
我在 django 中开发一个社交媒体应用程序,想重命名上传内容中的所有图像,以便更容易地重用它们(将它们放入 pdf 是最终目标,现在文件名与上传和我不知道如何将这些路径放入 pdf --> 解决方案可能是对它们进行编号)。
文件名应重命名为:postimg{num_post} 所有职位都有编号。具体编号或帖子应在图像文件的文件名末尾。
模型.py
def post_images(instance, filename):
ext = filename.split('.')[-1]
filename = "%s_%s.%s" % (instance.post.num_post, ext)
return os.path.join('uploads', filename)
class Post(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
num_post = models.IntegerField(default=0)
image = models.ImageField(upload_to='post_images')
caption = models.TextField(max_length=300)
created_at = models.DateTimeField(auto_now_add=True)
number_of_likes = models.IntegerField(default=0)
number_of_dislikes = models.IntegerField(default=0)
def __str__(self):
return self.caption
视图.py
def upload(request):
if request.method == 'POST':
#user = request.user.username
image = request.FILES.get('image_upload')
#--> how to rename the image file to "post{num_post}.jpg"
caption = request.POST['caption']
num_post = Post.objects.count()+1
new_post = Post.objects.create(image=image, caption=caption, num_post=num_post)
new_post.save()
#create pdf
buffer = io.BytesIO()
#get the image
#img_file = Image.open(f'{os.getcwd()}/{post.image.url}').convert('RGB')
#img_file = f'media/post_images/postimg{num_post}'
#x_start = 0
#y_start = 0
#saving it on the server
folder_path = f"media/post{num_post}.pdf"
folder_name = os.path.basename(folder_path)
p = canvas.Canvas(folder_name)
#p.drawImage(img_file, x_start, y_start, width=120, preserveAspectRatio=True, mask='auto')
p.drawString(200, 300, new_post.caption)
p.drawString(200, 100, str(new_post.created_at))
p.drawString(200, 600, str(new_post.id))
#p.drawText(new_post.caption)
#p.drawImage(new_post.image)
p.showPage()
p.save()
buffer.seek(0)
return redirect('/'), folder_path
else:
return redirect('/')
所以最后我应该能够通过使用将图像放入pdf中:
img_file = f'media/post_images/postimg{num_post}'
x_start = 0
y_start = 0
p.drawImage(img_file, x_start, y_start, width=120, preserveAspectRatio=True, mask='auto')
我已经能够通过使用现有文件名将图像转换为 pdf,但由于应该为每个帖子自动生成 pdf,我认为图像名称需要可变。
现在,它不起作用。图像没有重命名,但也没有错误显示。所以功能似乎没有达到图像?我如何让它发挥作用?
谢谢你的任何建议。 :) 我是 Django 的新手...任何解释都有帮助。
【问题讨论】:
标签: python django django-models file-rename image-upload