import zipfile from django import forms from django.core.exceptions import ValidationError from .models import MindFolder, MindMap MAX_XMIND_MB = 30 def descendant_ids(folder): found = set() stack = [folder.pk] while stack: parent_id = stack.pop() children = list( MindFolder.objects.filter(parent_id=parent_id).values_list("pk", flat=True) ) for child_id in children: if child_id not in found: found.add(child_id) stack.append(child_id) return found class MindFolderForm(forms.Form): id = forms.IntegerField(required=False, widget=forms.HiddenInput) name = forms.CharField( max_length=100, label="目录名称", widget=forms.TextInput(attrs={"class": "mm-input", "placeholder": "例如 C++、Python"}), ) slug = forms.CharField( required=False, max_length=100, label="URL 别名", widget=forms.TextInput(attrs={"class": "mm-input", "placeholder": "留空自动生成,建议英文"}), ) description = forms.CharField( required=False, label="简介", widget=forms.Textarea(attrs={ "class": "mm-input", "rows": 2, "placeholder": "这个目录学什么(可选)", }), ) parent = forms.ModelChoiceField( queryset=MindFolder.objects.none(), required=False, label="上级目录", empty_label="无上级目录", widget=forms.Select(attrs={"class": "mm-input"}), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) edit_id = None if self.is_bound: try: edit_id = int(self.data.get("id") or 0) except (TypeError, ValueError): edit_id = None elif self.initial.get("id"): try: edit_id = int(self.initial["id"]) except (TypeError, ValueError): edit_id = None queryset = MindFolder.objects.order_by("name") if edit_id: folder = MindFolder.objects.filter(pk=edit_id).first() if folder: queryset = queryset.exclude(pk__in={folder.pk} | descendant_ids(folder)) self.fields["parent"].queryset = queryset class MindMapUploadForm(forms.ModelForm): class Meta: model = MindMap fields = ["xmind_file", "title", "folder", "description"] widgets = { "xmind_file": forms.ClearableFileInput(attrs={ "class": "mm-file", "accept": ".xmind", }), "title": forms.TextInput(attrs={ "class": "mm-input", "placeholder": "留空则使用脑图根节点标题", }), "folder": forms.Select(attrs={"class": "mm-input"}), "description": forms.Textarea(attrs={ "class": "mm-input", "rows": 2, "placeholder": "一句话说明这份脑图(可选)", }), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["xmind_file"].required = True self.fields["title"].required = False self.fields["folder"].queryset = MindFolder.objects.order_by("name") self.fields["folder"].empty_label = "不归入目录" def clean_xmind_file(self): uploaded = self.cleaned_data["xmind_file"] name = uploaded.name or "" if not name.lower().endswith(".xmind"): raise ValidationError("只支持 .xmind 文件。") if uploaded.size and uploaded.size > MAX_XMIND_MB * 1024 * 1024: raise ValidationError("XMind 文件不能超过 {} MB。".format(MAX_XMIND_MB)) try: if not zipfile.is_zipfile(uploaded): raise ValidationError("不是有效的 XMind 文件。") except ValidationError: raise except Exception: raise ValidationError("不是有效的 XMind 文件。") finally: try: uploaded.seek(0) except Exception: pass return uploaded class MindMapEditForm(forms.ModelForm): class Meta: model = MindMap fields = ["title", "folder", "description"] widgets = { "title": forms.TextInput(attrs={"class": "mm-input"}), "folder": forms.Select(attrs={"class": "mm-input"}), "description": forms.Textarea(attrs={"class": "mm-input", "rows": 2}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["folder"].queryset = MindFolder.objects.order_by("name") self.fields["folder"].empty_label = "不归入目录"