【问题标题】:Django - [Errno 2] No such file or directory error: when attempting to save an uploaded file to a dynamic urlDjango - [Errno 2] 没有这样的文件或目录错误:尝试将上传的文件保存到动态 url 时
【发布时间】:2021-03-29 18:13:15
【问题描述】:

模型.py:

class Enterprise(models.Model):
    name = models.CharField(max_length = 100)
    def __str__(self):
        return f"{self.id}_{self.name}"

class Client(models.Model):
    name = models.CharField(max_length = 100)
    def __str__(self):
        return f"{self.id}_{self.name}"    

class Engagement(models.Model):
    name = models.CharField(max_length = 100    
    def __str__(self):
        return f"{self.id}_{self.name}"

class StockCount(models.Model):
    name = models.CharField(max_length = 100)    
    def __str__(self):
        return f"{self.name}"

class InventoryList(models.Model):
    UploadedFile = models.FileField(_('Upload Inventory Listing'), upload_to = file_upload_location, validators=[validate_file_extension], max_length = 500)
    enterprise = models.ForeignKey('Enterprise', on_delete=models.CASCADE, related_name = 'inventorylists')
    client = models.ForeignKey('Client', on_delete=models.CASCADE, related_name = 'inventorylists')
    engagement = models.ForeignKey('Engagement', on_delete=models.CASCADE, related_name = 'inventorylists')
    stockcount = models.ForeignKey('StockCount', on_delete=models.CASCADE, related_name = 'inventorylists')

views.py:

def upload(request):   
    if request.method == 'POST':
        form = InventoryListForm(request.POST, request.FILES)
        if form.is_valid():    
            # file is saved
            list = form.save(commit = False)
            list.enterprise = Enterprise.objects.get(pk = 1)
            list.client = Client.objects.get(pk = 1)
            list.engagement = Engagement.objects.get(pk = 1) 
            list.stockcount = StockCount.objects.get(pk = 1)   
            list.save() 
            return HttpResponse(f'You have just made a post request - {list.id}')   
        else:
            return render(request, "observe/upload.html", {"form": form})
    else: 
        return render(request, "observe/upload.html", {"form": InventoryListForm()})

forms.py:

class InventoryListForm(ModelForm):
    class Meta:
        model = InventoryList
        exclude = ['enterprise', 'client', 'engagement', 'stockcount']
    def __init__(self, *args, **kwargs):
        super(InventoryListForm, self).__init__(*args, **kwargs)

upload_to 可调用函数:

def file_upload_location(instance, filename):
    ext = filename.split('.')[-1]
    # return f"{instance.enterprise}/{instance.client}/{instance.engagement}/{instance.stockcount}/{filename}"
    # return f"{filename}"
    FileType = '\\Inventory List'
    name = str(filename)
    path = os.path.join(str(instance.enterprise), str(instance.client), str(instance.engagement), str(instance.stockcount))
    # return f"{path}/{filename}"
    # return path 
    print(f"The path is {path}")
    # return f"{path}/"
    # return '{0}/{1}/{2}/{3}/{4}'.format(str(instance.enterprise), str(instance.client), str(instance.engagement), str(instance.stockcount), filename)
    return os.path.join("%s" % str(instance.enterprise), "%s" % str(instance.client), "%s" % str(instance.engagement), "%s" % str(instance.stockcount), filename)

我已经尝试了可调用函数的多种变体(从上面函数的注释掉部分可以看出),但我仍然收到此错误。有趣的是,当我第一次上传文件并提交表单时,它可以工作。但是,我第二次尝试时,它给了我这个 errno2 错误。

完整的回溯如下:

[Errno 2] 没有这样的文件或目录:'C:\Users\bilal\Desktop\Inventory Observation Mobile Responsive Web Application\Inventory-observation-mobile-responsive-web-application\inventoryobservation\files\1_RSM Canada\PK752_Nuvera Corp\FY 2021_Prospectus work\London Count\Monthly_Sales_Reporting_Template_Tool_Start.xlsm'

似乎我的实际解决方案适用于某些 excel 文件而不适用于其他文件,并且基于对 excel 文件的进一步检查,我能够成功上传的 excel 文件似乎没有任何不同以及我无法上传的。

【问题讨论】:

    标签: django django-file-upload


    【解决方案1】:

    尝试使用这个:-

      UploadedFile = models.FileField(_('Upload Inventory Listing'), upload_to = 'file_upload_location', validators=[validate_file_extension], max_length = 500)
    

    而不是:-

      UploadedFile = models.FileField(_('Upload Inventory Listing'), upload_to = file_upload_location, validators=[validate_file_extension], max_length = 500)
    

    我编辑的内容:- 我在“file_upload_location”上添加了逗号。

    尝试使用它。

    【讨论】:

    • 感谢您的回复,但很遗憾,这不起作用。您建议的解决方案基本上最终创建了一个名为“file_to_upload”的文件夹。
    猜你喜欢
    • 1970-01-01
    • 2015-12-14
    • 2013-07-03
    • 1970-01-01
    • 2020-05-01
    • 2019-12-12
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多