diff --git a/sigi/apps/utils/__init__.py b/sigi/apps/utils/__init__.py new file mode 100644 index 0000000..2665d93 --- /dev/null +++ b/sigi/apps/utils/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +from django.db import models +from unicodedata import normalize + +class SearchField(models.TextField): + def pre_save(self, model_instance, add): + search_text = [] + for field_name in self.field_names: + val = unicode(to_ascii(getattr(model_instance, field_name))) + search_text.append(val) + value = u' '.join(search_text) + setattr(model_instance, self.name, value) + return value + def __init__(self, field_names, *args, **kwargs): + self.field_names = field_names + kwargs['editable'] = False + super(self.__class__, self).__init__(*args, **kwargs) + +def to_ascii(txt, codif='utf-8'): + if not isinstance(txt, basestring): + txt = unicode(txt) + if isinstance(txt, unicode): + txt = txt.encode('utf-8') + return normalize('NFKD', txt.decode(codif)).encode('ASCII','ignore') + +def queryset_ascii(self, request): + if 'q' in request.GET: + request.GET._mutable = True + request.GET['q'] = to_ascii(request.GET['q']) + return admin.ModelAdmin.queryset(self, request)