Django: How to allow a Suspicious File Operation / copy a file

后端 未结 4 556
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 01:54

I want to do a SuspiciousFileOperation which django disallows by default.

I am writing a command (to run via manage.py importfiles) to impo

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 02:44

    I haven't faced similar problem but related issue. I have recently upgraded Django 1.8 to 1.11.

    Now I am getting the following error if try to save a file in a model having FileField field:

    SuspiciousFileOperation at /api/send_report/ The joined path (/vagrant/tmp/test_file.pdf) is located outside of the base path component (/vagrant/media)

    My model where I want to save the file:

    class Report(BaseModel):
        file = models.FileField(max_length=200, upload_to=os.path.join(settings.REPORTS_URL, '%Y/week_%W/'))
        type = models.CharField(max_length=20, verbose_name='Type', blank=False, default='', db_index=True)
    

    I am trying following codes to save the file from tmp folder which is not located in MEDIA_ROOT:

    from django.core.files import File
    
    filepath = "/vagrant/tmp/test_file.pdf"
    file = File(open(filepath, "rb"))
    report_type = "My_report_type"
    report = Report.objects.create(
        file=file,
        type=report_type,
    )
    

    What I have done to solve the issue:

    import os
    from django.core.files import File
    
    filepath = "/vagrant/tmp/test_file.pdf"
    file = File(open(filepath, "rb"))
    file_name = os.path.basename(file.name)
    report_type = "My_report_type"
    report = Report.objects.create(
        type=report_type,
    )
    report.file.save(file_name, file, save=True)
    

    Hope it will help someone.

提交回复
热议问题