38 lines
1.3 KiB
Python
38 lines
1.3 KiB
Python
from pathlib import Path
|
|
|
|
from django import forms
|
|
|
|
from apps.scenarios.services import ScenarioNotFound, get_scenario
|
|
from apps.scenarios.services import list_scenarios
|
|
|
|
SUPPORTED_EXTENSIONS = {".txt", ".md", ".pdf", ".docx"}
|
|
|
|
|
|
class DocumentUploadForm(forms.Form):
|
|
# 使用 ChoiceField 让表单自己维护场景选项,
|
|
# 这样模板、校验和后续扩展都能围绕一个入口完成。
|
|
scenario_id = forms.ChoiceField(label="场景", choices=())
|
|
file = forms.FileField(label="文件")
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
self.fields["scenario_id"].choices = [
|
|
(scenario["id"], scenario["name"])
|
|
for scenario in list_scenarios()
|
|
]
|
|
|
|
def clean_scenario_id(self):
|
|
scenario_id = self.cleaned_data["scenario_id"]
|
|
try:
|
|
get_scenario(scenario_id)
|
|
except ScenarioNotFound as exc:
|
|
raise forms.ValidationError("场景不存在") from exc
|
|
return scenario_id
|
|
|
|
def clean_file(self):
|
|
uploaded_file = self.cleaned_data["file"]
|
|
extension = Path(uploaded_file.name).suffix.lower()
|
|
if extension not in SUPPORTED_EXTENSIONS:
|
|
raise forms.ValidationError("仅支持 .txt、.md、.pdf 和 .docx 文件")
|
|
return uploaded_file
|