2019-08-11 07:22:22 +00:00
|
|
|
# -*- mode: python; coding: utf-8 -*-
|
|
|
|
# Copyright (C) 2017-2019 by BDE ENS Paris-Saclay
|
|
|
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
|
|
|
|
"""
|
|
|
|
Based on https://github.com/secnot/django-isbn-field
|
|
|
|
"""
|
|
|
|
|
|
|
|
from django.core.validators import EMPTY_VALUES
|
|
|
|
from django.db.models import CharField
|
|
|
|
from django.utils.translation import gettext_lazy as _
|
|
|
|
|
|
|
|
from .validators import isbn_validator
|
|
|
|
|
|
|
|
|
|
|
|
class ISBNField(CharField):
|
|
|
|
description = _("ISBN-10 or ISBN-13")
|
|
|
|
|
|
|
|
def __init__(self, clean_isbn=True, *args, **kwargs):
|
|
|
|
self.clean_isbn = clean_isbn
|
|
|
|
kwargs['max_length'] = kwargs[
|
|
|
|
'max_length'] if 'max_length' in kwargs else 28
|
|
|
|
kwargs['verbose_name'] = kwargs[
|
|
|
|
'verbose_name'] if 'verbose_name' in kwargs else u'ISBN'
|
|
|
|
kwargs['validators'] = [isbn_validator]
|
2019-08-16 17:44:27 +00:00
|
|
|
super().__init__(*args, **kwargs)
|
2019-08-11 07:22:22 +00:00
|
|
|
|
|
|
|
def formfield(self, **kwargs):
|
|
|
|
defaults = {
|
|
|
|
'min_length': 10,
|
|
|
|
'validators': [isbn_validator],
|
|
|
|
}
|
|
|
|
defaults.update(kwargs)
|
2019-08-16 17:44:27 +00:00
|
|
|
return super().formfield(**defaults)
|
2019-08-11 07:22:22 +00:00
|
|
|
|
|
|
|
def deconstruct(self):
|
2019-08-16 17:44:27 +00:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2019-08-11 07:22:22 +00:00
|
|
|
# Only include clean_isbn in kwarg if it's not the default value
|
|
|
|
if not self.clean_isbn:
|
|
|
|
kwargs['clean_isbn'] = self.clean_isbn
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
|
|
|
def pre_save(self, model_instance, add):
|
|
|
|
"""
|
|
|
|
Remove dashes, spaces, and convert isbn to uppercase before saving
|
|
|
|
when clean_isbn is enabled
|
|
|
|
"""
|
|
|
|
value = getattr(model_instance, self.attname)
|
|
|
|
if self.clean_isbn and value not in EMPTY_VALUES:
|
|
|
|
cleaned_isbn = value.replace(' ', '').replace('-', '').upper()
|
|
|
|
setattr(model_instance, self.attname, cleaned_isbn)
|
2019-08-16 17:44:27 +00:00
|
|
|
return super().pre_save(model_instance, add)
|
2019-08-11 07:22:22 +00:00
|
|
|
|
|
|
|
def __unicode__(self):
|
|
|
|
return self.value
|