Skip to content

add Nh3Char(models.CharField) #44

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -26,6 +26,7 @@ share/python-wheels/
.installed.cfg
*.egg
MANIFEST
.idea/

# PyInstaller
# Usually these files are written by a python script from a template
78 changes: 77 additions & 1 deletion src/django_nh3/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import warnings
from collections.abc import Callable
from typing import Any

@@ -13,7 +14,82 @@
from . import forms


class Nh3Field(models.TextField):
class Nh3Text(models.TextField):
def __init__(
self,
attributes: dict[str, set[str]] = {},
attribute_filter: Callable[[str, str, str], str] | None = None,
clean_content_tags: set[str] = set(),
link_rel: str = "",
strip_comments: bool = False,
tags: set[str] = set(),
*args: Any,
**kwargs: Any,
) -> None:
super().__init__(*args, **kwargs)

self.nh3_options = {
"attributes": attributes,
"attribute_filter": attribute_filter,
"clean_content_tags": clean_content_tags,
"link_rel": link_rel,
"strip_comments": strip_comments,
"tags": tags,
}

def formfield(
self, form_class: FormField = forms.Nh3Field, **kwargs: Any
) -> FormField:
"""Makes the field for a ModelForm"""

# If field doesn't have any choices add kwargs expected by Nh3Field.
if not self.choices:
kwargs.update(
{
"max_length": self.max_length,
"attributes": self.nh3_options.get("attributes"),
"attribute_filter": self.nh3_options.get("attribute_filter"),
"clean_content_tags": self.nh3_options.get("clean_content_tags"),
"link_rel": self.nh3_options.get("link_rel"),
"strip_comments": self.nh3_options.get("strip_comments"),
"tags": self.nh3_options.get("tags"),
"required": not self.blank,
}
)

return super().formfield(form_class=form_class, **kwargs)

def pre_save(self, model_instance: Model, add: bool) -> Any:
data = getattr(model_instance, self.attname)
if data is None:
return data
clean_value = nh3.clean(data, **self.nh3_options) if data else ""
setattr(model_instance, self.attname, mark_safe(clean_value))
return clean_value

def from_db_value(
self,
value: Any,
expression: Expression,
connection: BaseDatabaseWrapper,
) -> Any:
if value is None:
return value
# Values are sanitised before saving, so any value returned from the DB
# is safe to render unescaped.
return mark_safe(value)


def Nh3Field(*args: Any, **kwargs: Any) -> Nh3Text:
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've done a little research on the deprecation of a class now. So I think keep Nh3Field as a class.

Add a docstring note of the deprecation along with perhaps adding the typing decorator would be a good idea;

from typing import TypeVar
from typing_extensions import deprecated

@deprecated("Use Nh3Text instead")
class Nh3Field:
    """
    .. deprecated:: 0.2.0
       Use :class:`Nh3Text` instead.
    """
    pass

Then raise the deprecation in the __init__ similar to;

import warnings

class Nh3Field:
    def __init__(self):
        warnings.warn(
            "Nh3Field is deprecated and will be removed in a future version. Use Nh3Text instead.",
            DeprecationWarning,
            stacklevel=2
        )

And to prevent this being a breaking change, it could inherit Nh3Text;

class Nh3Field(Nh3Text):

warnings.filterwarnings(
action="default",
message="Nh3Field is deprecated, use Nh3Text instead",
category=FutureWarning,
)
return Nh3Text(*args, **kwargs)


class Nh3Char(models.CharField):
def __init__(
self,
attributes: dict[str, set[str]] = {},
12 changes: 6 additions & 6 deletions tests/test_models.py → tests/test_models_charfield.py
Original file line number Diff line number Diff line change
@@ -3,17 +3,17 @@
from django.test import TestCase
from django.utils.safestring import SafeString

from django_nh3.models import Nh3Field
from django_nh3.models import Nh3Char


class Nh3Content(models.Model):
"""NH3 test model"""

content = Nh3Field(
content = Nh3Char(
strip_comments=True,
)
blank_field = Nh3Field(blank=True)
null_field = Nh3Field(blank=True, null=True)
blank_field = Nh3Char(blank=True)
null_field = Nh3Char(blank=True, null=True)


class Nh3ContentModelForm(ModelForm):
@@ -28,8 +28,8 @@ class Nh3NullableContent(models.Model):
"""NH3 test model"""

CHOICES = (("f", "first choice"), ("s", "second choice"))
choice = Nh3Field(choices=CHOICES, blank=True)
content = Nh3Field(blank=True, null=True)
choice = Nh3Char(choices=CHOICES, blank=True)
content = Nh3Char(blank=True, null=True)


class Nh3NullableContentModelForm(ModelForm):
147 changes: 147 additions & 0 deletions tests/test_models_textfield.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
from django.db import models
from django.forms import ModelForm
from django.test import TestCase
from django.utils.safestring import SafeString

from django_nh3.models import Nh3Text


class Nh3Content(models.Model):
"""NH3 test model"""

content = Nh3Text(
strip_comments=True,
)
blank_field = Nh3Text(blank=True)
null_field = Nh3Text(blank=True, null=True)


class Nh3ContentModelForm(ModelForm):
"""NH3 test model form"""

class Meta:
model = Nh3Content
fields = ["content"]


class Nh3NullableContent(models.Model):
"""NH3 test model"""

CHOICES = (("f", "first choice"), ("s", "second choice"))
choice = Nh3Text(choices=CHOICES, blank=True)
content = Nh3Text(blank=True, null=True)


class Nh3NullableContentModelForm(ModelForm):
"""NH3 test model form"""

class Meta:
model = Nh3NullableContent
fields = ["choice"]


class TestNh3ModelField(TestCase):
"""Test model field"""

def test_cleaning(self):
"""Test values are sanitized"""
test_data = {
"html_data": "<h1>Heading</h1>",
"no_html": "Heading",
"html_comment": "<!-- this is a comment -->",
}
expected_values = {
"html_data": "Heading",
"no_html": "Heading",
"html_comment": "",
}

for key, value in test_data.items():
obj = Nh3Content.objects.create(content=value)
self.assertEqual(obj.content, expected_values[key])

def test_retrieved_values_are_template_safe(self):
obj = Nh3Content.objects.create(content="some content")
obj.refresh_from_db()
self.assertIsInstance(obj.content, SafeString)
obj = Nh3Content.objects.create(content="")
obj.refresh_from_db()
self.assertIsInstance(obj.content, SafeString)

def test_saved_values_are_template_safe(self):
obj = Nh3Content(content="some content")
obj.save()
self.assertIsInstance(obj.content, SafeString)
obj = Nh3Content(content="")
obj.save()
self.assertIsInstance(obj.content, SafeString)

def test_saved_none_values_are_none(self):
obj = Nh3Content(null_field=None)
obj.save()
self.assertIsNone(obj.null_field)


class TestNh3NullableModelField(TestCase):
"""Test model field"""

def test_cleaning(self):
"""Test values are sanitized"""
test_data = {
"none": None,
"empty": "",
"whitespaces": " ",
"linebreak": "\n",
}
expected_values = {
"none": None,
"empty": "",
"whitespaces": " ",
"linebreak": "\n",
}

for key, value in test_data.items():
obj = Nh3NullableContent.objects.create(content=value)
self.assertEqual(obj.content, expected_values[key])


class TestNh3ModelFormField(TestCase):
"""Test model form field"""

def test_cleaning(self):
"""Test values are sanitized"""
test_data = {
"html_data": "<h1>Heading</h1>",
"no_html": "Heading",
"spacing": " Heading ",
}
expected_values = {
"html_data": "Heading",
"no_html": "Heading",
"spacing": "Heading",
}

for key, value in test_data.items():
form = Nh3ContentModelForm(data={"content": value})
self.assertTrue(form.is_valid())
obj = form.save()
self.assertEqual(obj.content, expected_values[key])

def test_stripped_comments(self):
"""Content field strips comments so ensure they aren't allowed"""

self.assertFalse(
Nh3ContentModelForm(
data={"content": "<!-- this is a comment -->"}
).is_valid()
)

def test_field_choices(self):
"""Content field strips comments so ensure they aren't allowed"""
test_data = dict(Nh3NullableContent.CHOICES)

for key, value in test_data.items():
form = Nh3NullableContentModelForm(data={"choice": key})
self.assertTrue(form.is_valid())
obj = form.save()
self.assertEqual(obj.get_choice_display(), value)