File size: 1,847 Bytes
ce4b573 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import force_text, python_2_unicode_compatible
from django.utils.six import string_types
from django.utils.translation import ugettext_lazy as _
import likert_field.forms as forms
@python_2_unicode_compatible
class LikertField(models.IntegerField):
"""A Likert field is simply stored as an IntegerField"""
description = _('Likert item field')
def __init__(self, *args, **kwargs):
"""
LikertField stores items with no answer as NULL
By default responses are optional, so 'blank' is True
"""
if kwargs.get('null', True):
kwargs['null'] = True
if kwargs.get('blank', True):
kwargs['blank'] = True
super(LikertField, self).__init__(*args, **kwargs)
def __str__(self):
return "%s" % force_text(self.description)
def get_prep_value(self, value):
"""
Perform preliminary non-db specific value checks and conversions.
The field expects a number as a string (ie. '2'). Unscored fields are
empty strings and are stored as NULL
"""
if value is None:
return None
if isinstance(value, string_types) and len(value) == 0:
return None
value = int(value)
if value < 0:
value = 0
return value
def formfield(self, **kwargs):
defaults = {
'min_value': 0,
'form_class': forms.LikertFormField
}
defaults.update(kwargs)
return super(LikertField, self).formfield(**defaults)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^likert_field\.models\.LikertField"])
|