Nessuna descrizione

forms.py 2.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from django import forms
  2. from django.contrib.auth import get_user_model
  3. from crispy_forms.helper import FormHelper
  4. from crispy_forms.layout import Layout, Field
  5. from markdownfield.widgets import MDEWidget
  6. from .widgets import ImagePreviewWidget
  7. from .models import Post, PostCategory
  8. from mptt.forms import TreeNodeChoiceField
  9. User = get_user_model()
  10. class PostCategoryForm(forms.ModelForm):
  11. class Meta:
  12. model = PostCategory
  13. fields = ["name", "slug", "parent", "description"]
  14. def __init__(self, *args, **kwargs):
  15. super().__init__(*args, **kwargs)
  16. self.helper = FormHelper()
  17. self.helper.form_tag = False
  18. self.helper.layout = Layout(
  19. Field("name"),
  20. Field("slug"),
  21. Field("parent"),
  22. Field("description"),
  23. )
  24. def __init__(self, *args, **kwargs):
  25. super().__init__(*args, **kwargs)
  26. # Use TreeNodeChoiceField for hierarchical parent selection
  27. self.fields["parent"] = TreeNodeChoiceField(
  28. queryset=PostCategory.objects.all(), required=False, level_indicator="— "
  29. )
  30. class PostForm(forms.ModelForm):
  31. tags = forms.CharField(label="Tags", required=False, help_text="Comma-separated")
  32. class Meta:
  33. model = Post
  34. fields = [
  35. "title",
  36. "slug",
  37. "category",
  38. "author",
  39. "excerpt",
  40. "feature_image",
  41. "content",
  42. "status",
  43. "published_at",
  44. ]
  45. widgets = {
  46. "published_at": forms.DateTimeInput(attrs={"type": "datetime-local"}),
  47. "content": MDEWidget(attrs={"rows": 20}),
  48. "feature_image": ImagePreviewWidget(),
  49. }
  50. def __init__(self, *args, **kwargs):
  51. super().__init__(*args, **kwargs)
  52. self.helper = FormHelper()
  53. self.helper.form_tag = False
  54. self.helper.layout = Layout(
  55. Field("title"),
  56. Field("slug"),
  57. Field("category"),
  58. Field("author"),
  59. Field("excerpt"),
  60. Field("feature_image"),
  61. Field("content"),
  62. Field("status"),
  63. Field("published_at"),
  64. Field("tags"),
  65. )
  66. # Initialize tags from instance
  67. if self.instance and getattr(self.instance, "pk", None):
  68. try:
  69. names = list(self.instance.tags.names())
  70. self.fields["tags"].initial = ", ".join(names)
  71. except Exception:
  72. self.fields["tags"].initial = ""
  73. def save(self, commit=True):
  74. obj = super().save(commit)
  75. tags = [t.strip() for t in self.cleaned_data.get("tags", "").split(",") if t.strip()]
  76. try:
  77. if commit:
  78. obj.tags.set(tags)
  79. except Exception:
  80. pass
  81. return obj