Skip to content

Commit

Permalink
Add some QoL improvements to the model field
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiask committed Mar 11, 2024
1 parent 925dba0 commit 8e0ecb6
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ Next version
~~~~~~~~~~~~

- Fixed the initialization in Django admin inlines.
- Added a server-side sanitization callback to the ``ProseEditorField``.
- Automatically added a ``get_*_excerpt`` model method to models using the
``ProseEditorField`` as a convenience.


`0.1`_ (2024-03-11)
Expand Down
31 changes: 28 additions & 3 deletions django_prose_editor/fields.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,43 @@
from django import forms
from django.db import models
from django.utils.html import strip_tags
from django.utils.text import Truncator

from django_prose_editor.widgets import ProseEditorWidget


def _identity(x):
return x


class ProseEditorField(models.TextField):
def formfield(self, **kwargs):
defaults = {"form_class": ProseEditorFormField} | kwargs
return super().formfield(**defaults)
def __init__(self, *args, **kwargs):
self.sanitize = kwargs.pop("sanitize", _identity)
super().__init__(*args, **kwargs)

def clean(self, value, instance):
return self.sanitize(super().clean(value, instance))

def contribute_to_class(self, cls, name, **kwargs):
"""Add a ``get_*_excerpt`` method to models which returns a
de-HTML-ified excerpt of the contents of this field"""
super().contribute_to_class(cls, name, **kwargs)
setattr(
cls,
f"get_{name}_excerpt",
lambda self, words=10, truncate=" ...": Truncator(
strip_tags(getattr(self, name))
).words(words, truncate=truncate),
)

def deconstruct(self):
name, _path, args, kwargs = super().deconstruct()
return (name, "django.db.models.TextField", args, kwargs)

def formfield(self, **kwargs):
defaults = {"form_class": ProseEditorFormField} | kwargs
return super().formfield(**defaults)


class ProseEditorFormField(forms.CharField):
widget = ProseEditorWidget
Expand Down

0 comments on commit 8e0ecb6

Please sign in to comment.