如何在 Django 中上传文件并根据格式将它们保存(并在信号中采取其他操作 - post_save
)在不同的位置?(JPEG和文档)
def upload(request):
user = request.user
upload_form = UploadForm(request.POST or None, request.FILES or None)
if request.method == "POST":
if upload_form.is_valid():
my_model = upload_form.save(commit=False)
my_model.user = user
my_model.save()
楷模:
class FileStore(models.Model):
user = models.ForeignKey(User)
standard = models.FileField(upload_to="standard")
after_operation = models.FileField(upload_to="after_ocr",blank=True, null=True)
信号:
@receiver(post_save, sender=FileStore)
def my_handler(sender,instance, **kwargs):
if kwargs['created']:
text= image_to_string(Image.open(instance.standard))
...
instance.after_operation = File(text_file)
instance.save()
我想如果文件是.doc
或.pdf
只保存在standard
字段中,如果文件是.jpeg
或.png
我需要运行我的信号功能。