Skip to content

Commit

Permalink
Support plain Django forms. #211
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiocaccamo committed Jan 27, 2025
1 parent 32eeb53 commit 34af138
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
16 changes: 16 additions & 0 deletions colorfield/forms.py
Original file line number Diff line number Diff line change
@@ -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)
6 changes: 6 additions & 0 deletions tests/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django import forms
from colorfield.forms import ColorField


class BasicForm(forms.Form):
color = ColorField(initial="#FF0000")
54 changes: 54 additions & 0 deletions tests/test_basic_form.py
Original file line number Diff line number Diff line change
@@ -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)

0 comments on commit 34af138

Please sign in to comment.