如何在 Django 中输入正确的文件路径(远程或本地服务器)提供验证检查?



我有一个表单,如果它采用有效的格式(无论它在远程/本地服务器中,即FTP(并且不包含任何特定文件,即<'file_directory'>\pic.png',它应该接受文件路径(目录(。如果路径无效,则不应将其保存到模型中。

我尝试了以下方法:

views.py:

from pathlib import Path as PATH  #using pathlib since it's used on all OS platforms.
def home(request):
if request.method == 'POST':
form = PForm(request.POST) 
if form.is_valid():  
user_id = request.user.id  
folder_path = form.cleaned_data['folder_path']
path = PATH(folder_path)  #using pathlib module to check if the folder_path exists.
root, extension = os.path.splitext(folder_path)  #checks if extension is seen in folder_path.
if extension or not path.resolve(strict=True): 
messages.warning(request, "Path is not valid.")
return redirect('home')
else:
#save the path to the model
else:
form = PForm()
return render(request, 'template/home.html, {'form' : form})

检查文件扩展名的验证有效,但是一旦我输入无效的目录路径,就会收到此错误:

Exception Type: FileNotFoundError
Exception Value: [WinError 3] The system cannot find the path specified: '<invalid pathname>'  #eg 'var/html/www/pictures'

如何实现更好的验证检查和处理错误的方法?提前谢谢你。

您可以捕获异常并相应地处理,如下所示。

try:
path = PATH(folder_path)
root, extension = os.path.splitext(folder_path)
....
# capture exceptions here (you can add multiple)
except FileNotFoundError:
# handle exceptions as needed here
messages.warning(request, "Path is not valid.")
return redirect('home')

相关内容

  • 没有找到相关文章

最新更新