Skip to content
Open
Show file tree
Hide file tree
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
6 changes: 6 additions & 0 deletions isbn_field/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,11 @@ def pre_save(self, model_instance, add):
setattr(model_instance, self.attname, cleaned_isbn)
return super(ISBNField, self).pre_save(model_instance, add)

def to_python(self, value):
if self.clean_isbn and value not in EMPTY_VALUES:
return value.replace(' ', '').replace('-', '').upper()
else:
return value

def __unicode__(self):
return self.value
5 changes: 5 additions & 0 deletions tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ class CleanISBNModel(models.Model):
isbn = ISBNField() # clean_isbn=True (default)


class UniqueCleanISBNModel(models.Model):

isbn = ISBNField(unique=True) # clean_isbn=True (default)


class DirtyISBNModel(models.Model):
id = models.BigAutoField(primary_key=True)
isbn = ISBNField(clean_isbn=False)
Expand Down
18 changes: 14 additions & 4 deletions tests/tests.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
from django.core.exceptions import ValidationError
from isbn_field.validators import ISBNValidator
from isbn_field import ISBNField

from django.test import TestCase

from .models import CleanISBNModel, DirtyISBNModel, BlankISBNModel, BlankNullISBNModel
from isbn_field.validators import ISBNValidator
from .models import CleanISBNModel, DirtyISBNModel, BlankISBNModel, BlankNullISBNModel, UniqueCleanISBNModel


class ISBNValidatorTest(TestCase):

Expand Down Expand Up @@ -71,6 +70,17 @@ def test_isbn_field_clean(self):
m = DirtyISBNModel.objects.create(isbn=original)
self.assertEqual(m.isbn, original)

def test_isbn_field_unique_clean(self):
UniqueCleanISBNModel.objects.create(isbn='0-765-348-276')

with self.assertRaises(ValidationError):
instance = UniqueCleanISBNModel(isbn='0-765-348-276')
instance.full_clean()
# The previous line should throw the expected exception,
# but if it does not, the line below throwing an IntegrityError
# serves as a sanity check for this test.
UniqueCleanISBNModel.objects.create(isbn='0-765-348-276')

def test_isbn_field_blank(self):
"""Test empty values are accepted when blank=True"""
m = BlankISBNModel.objects.create(isbn="")
Expand Down