from pathlib import Path from django import forms from apps.scenarios.services import ScenarioNotFound, get_scenario SUPPORTED_EXTENSIONS = {".txt", ".md", ".pdf", ".docx"} class DocumentUploadForm(forms.Form): scenario_id = forms.CharField(label="场景") file = forms.FileField(label="文件") 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