所以我已经创建了一个pdf文档,它应该保存在媒体/帖子中。路径已经在函数中,但是pdf没有保存在那里,而是保存在主项目文件夹中。我在这里忽略了什么?
关于def的一点解释:帖子被创建并上传到提要,而帖子中的图像被重命名并放入另一个文件夹。另外,一个pdf文件也被创建,其中包含了发布的材料。我如何确定这个pdf文件在服务器上的位置?我以为它是用path_name和path_file解决的,但它不起作用。提前感谢。
def post_create(request):
if request.method == 'POST':
form = PostCreateForm(request.POST, request.FILES)
if form.is_valid():
form.cleaned_data['num_post'] = Post.objects.count() + 1
Post.objects.create(**form.cleaned_data)
else:
form = PostCreateForm()
return render(request, 'index.html', {'form': form})
def upload(request):
if request.method == 'POST':
image = request.FILES.get('image_upload')
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()
x_start = 100
y_start = 10
folder_path = f"media/postings/post{num_post}.pdf"
folder_name = os.path.basename(folder_path)
print(folder_path)
p = canvas.Canvas(folder_name, pagesize=A4,)
#p == request.FILES.get('postings')
p.drawImage(ImageReader(image.file), x_start, y_start, width=420, preserveAspectRatio=True, mask='auto')
p.drawString(150, 650, new_post.caption)
p.drawString(100, 650, "caption:")
p.drawString(100, 170, str(new_post.created_at))
p.drawString(200, 700, str(num_post))
p.drawString(100, 700, "post no.:")
p.drawString(250, 700, "//")
p.drawString(100, 690, "===========================================================")
p.drawString(300, 700, str(new_post.id))
#p.showPage()
p.save()
buffer.seek(0)
#return render(request, '/', {'folder_name': folder_name, })
return redirect('/'), folder_path
else:
return redirect('/')
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)
like_list = models.TextField(max_length=300)
#likes_row = models.TextField(max_length=1000, default="hi")
number_of_dislikes = models.IntegerField(default=0)
interaction_count = models.IntegerField(default=0)
#downloads = models.FileField(upload_to='postings', blank=True, null=True)
@property
def filename(self):
return os.path.basename(self.image.name).split('.')[0]
def __str__(self):
return self.caption
1条答案
按热度按时间wljmcqd81#
basename只返回代码中路径“postxxx.pdf”的右边部分,并将其移交给canvas...