【发布时间】:2021-05-21 03:00:20
【问题描述】:
我对 django 的概念及其功能非常陌生 所以我遇到了一个项目,它可以很容易地帮助人们使用 FileField Upload to 将文件上传到目录,但对我来说它不起作用,我尝试了不同的方法来修改它,但我仍然不确定会出现错误。
所以有人请指导我
这是我的代码:
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'
在 html 中:enctype="multipart/form-data" method="POST"
。我在google上搜索时唯一显示的就是这个,我的代码和google的一样,不知道是否无法识别错误。
所以在我迁移并运行它之后,它不会给我任何错误,但是当我检查文件夹时它是空的
谁能帮帮我
编辑代码后出现错误: 由于文件未复制到upload_files,当我尝试将文件复制到另一个网络共享驱动器时,它会抛出错误,说upload_files 中没有文件
【问题讨论】:
标签: python django file-upload filefield