diff --git a/colorfield/forms.py b/colorfield/forms.py new file mode 100644 index 0000000..ce2b20e --- /dev/null +++ b/colorfield/forms.py @@ -0,0 +1,16 @@ +from django import forms + +from colorfield.validators import color_hex_validator +from colorfield.widgets import ColorWidget + + +class ColorField(forms.CharField): + default_validators = [ + color_hex_validator, + ] + + def __init__(self, *args, **kwargs): + validator = kwargs.pop("validator", color_hex_validator) + self.default_validators = [validator] + kwargs.setdefault("widget", ColorWidget()) + super().__init__(*args, **kwargs) diff --git a/tests/forms.py b/tests/forms.py new file mode 100644 index 0000000..0edbea3 --- /dev/null +++ b/tests/forms.py @@ -0,0 +1,6 @@ +from django import forms +from colorfield.forms import ColorField + + +class BasicForm(forms.Form): + color = ColorField(initial="#FF0000") diff --git a/tests/test_basic_form.py b/tests/test_basic_form.py new file mode 100644 index 0000000..c0b299e --- /dev/null +++ b/tests/test_basic_form.py @@ -0,0 +1,54 @@ +from django.test import TestCase +from tests.forms import BasicForm + + +class BasicFormTest(TestCase): + def test_color_field_initial_value(self): + """ + Test that the color field has the correct initial value. + """ + form = BasicForm() + self.assertEqual(form.fields["color"].initial, "#FF0000") + + def test_color_field_valid_data(self): + """ + Test that the form is valid with correct HEX color data. + """ + data = {"color": "#00FF00"} + form = BasicForm(data=data) + self.assertTrue(form.is_valid()) + self.assertEqual(form.cleaned_data["color"], "#00FF00") + + def test_color_field_invalid_data(self): + """ + Test that the form is invalid with incorrect HEX color data. + """ + # Test invalid HEX color (missing #) + data = {"color": "00FF00"} + form = BasicForm(data=data) + self.assertFalse(form.is_valid()) + self.assertIn("color", form.errors) + + # Test invalid HEX color (invalid characters) + data = {"color": "#ZZZZZZ"} + form = BasicForm(data=data) + self.assertFalse(form.is_valid()) + self.assertIn("color", form.errors) + + def test_color_field_empty_data(self): + """ + Test that the form is invalid when the color field is empty. + """ + data = {"color": ""} + form = BasicForm(data=data) + self.assertFalse(form.is_valid()) + self.assertIn("color", form.errors) + + def test_color_field_widget_rendering(self): + """ + Test that the color field widget renders correctly. + """ + form = BasicForm() + rendered_form = form.as_p() + self.assertIn('type="text"', rendered_form) + self.assertIn('value="#FF0000"', rendered_form)