Django文件未使用FileField上传(上传到=) [英] Django file not uploaded using FileField(upload to=)

查看:104
本文介绍了Django文件未使用FileField上传(上传到=)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Django概念及其功能来说是非常新的因此,我遇到了一个项目,该项目将很容易地帮助人们使用FileField Upload to将文件上传到目录,但是对我来说,它无法正常工作,我尝试了多种修改方式,但是仍然不确定错误会越来越严重.

am very new to concepts of django and it's functionalities so i came across a project which will easily help one to upload a file to a directory using FileField Upload to , but for me it is not working , i tried different ways i modifed it but still i am not sure about the error am getting .

所以有人请引导我

这是我的代码:

Models.py

class UploadedFiles(models.Model):
    files_to_upload = models.FileField(upload_to='uploaded_files/', default=None, validators=[validate_file])
    path = models.CharField(max_length=100)
    server = MultiSelectField(choices=server_list)

    SalesforceTicket = models.ForeignKey(SalesforceTicket, related_name="files", on_delete=models.CASCADE)

    def __str__(self):
        return str(self.SalesforceTicket)

forms.py

class FilesForm(forms.ModelForm):
    class Meta:
        model = UploadedFiles
        fields = ['files_to_upload', 'path', 'server']

    # called on validation of the form
    def clean(self):
        # run the standard clean method first
        cleaned_data = super(FilesForm, self).clean()
        files_to_upload = cleaned_data.get("files_to_upload")
        path = cleaned_data.get("path")
        server = cleaned_data.get("server")
        # print(files_to_upload)
        # print(path)
        # print(server)
        new_path = path.replace(':', '$', 1)
        # print(new_path)
        mode = 0o666
        for s in server:
            s = r'\\' + s
            unc_path = os.path.join(s, new_path)
            print("hello"+unc_path)
            #unc_path = os.mkdir(unc_path, mode)
        isdir = os.path.isdir(unc_path)

        if isdir:
            print("ok")
        else:
            unc_path = os.mkdir(unc_path, mode)
        return cleaned_data

Views.py

def files(request):
    num_of_files = 1
    filled_multi_file_form = MultipleForm(request.GET)
    if filled_multi_file_form.is_valid():
        num_of_files = filled_multi_file_form.cleaned_data['num_of_files']

    FilesFormSet = formset_factory(FilesForm, extra=num_of_files)
    formset = FilesFormSet()

    if request.method == 'POST':
        filled_form = SnippetForm(request.POST, request.FILES)
       
        filled_formset = FilesFormSet(request.POST, request.FILES)
        if filled_form.is_valid() and filled_formset.is_valid():
                     print"hi"

在settings.py中,我加入了MEDIA_ROOT = 'C:\ newform-16oct '

in settings.py , i included MEDIA_ROOT = 'C:\newform-16oct'

和html中的内容: enctype ="multipart/form-data";method ="POST"

and in html :enctype="multipart/form-data" method="POST"

.这是我在Google上进行搜索时唯一显示的内容,并且我的代码与google中的代码相同,不知道是否无法识别错误.

. Only thing that shows when i search on google is this , and my code is same as the one that is in google , don know whether am not able to identify error .

因此,在我迁移并运行此文件后,它不会引发任何错误,但是当我检查文件夹为空

so after i migrate and run this , it is not throwing me any error , but when i check the folder it is empty

任何人都可以帮助我

编辑代码后出现错误:由于该文件未复制到upload_files中,因此当我尝试将文件复制到另一个网络共享驱动器时,会抛出错误,提示upload_files中没有文件

Error got after editing the code : since the file is not copied to upload_files , when i try to copy the file to another network shared drive it is throwing me error , saying there is no file inside upload_files

因此,如果我尝试使用django管理员添加,这使我陷入错误之下

so if i try to add using django admin , it is thrwoing me below error

推荐答案

由于您创建了可生成新目录的脚本,因此该文件夹将保持为空,但从不要求将文件保存在此处.

The folder will remain empty since you made a script that generates a new directory, but never do you ask to save that file there.

但是我认为您在错误的位置解决了问题.该表格不需要处理.Django模型可以处理此问题:您可以将函数作为值传递给

However I think you are solving the problem at the wrong location. The form does not need to handle that. A Django model can handle this: you can pass a function as value for the upload_to=… parameter [Django-doc]:

class UploadedFiles(models.Model):
    def file_path(self, filename):
        return f'uploaded_files/{self.server}/{self.path.replace(":","$", 1)}/{filename}'
        
    files_to_upload = models.FileField(
        upload_to=file_path,
        default=None,
        validators=[validate_file]
    )
    path = models.CharField(max_length=100)
    server = MultiSelectField(choices=server_list)

    SalesforceTicket = models.ForeignKey(
        SalesforceTicket,
        related_name='files',
        on_delete=models.CASCADE
    )

    def __str__(self):
        return str(self.SalesforceTicket)

或类似的东西.

这篇关于Django文件未使用FileField上传(上传到=)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆