translation update
[redakcja.git] / apps / forms_builder / forms / utils.py
1 from __future__ import unicode_literals
2
3 from django.template.defaultfilters import slugify as django_slugify
4 from importlib import import_module
5 from unidecode import unidecode
6
7
8 # Timezone support with fallback.
9 try:
10     from django.utils.timezone import now
11 except ImportError:
12     from datetime import datetime
13     now = datetime.now
14
15
16 def slugify(s):
17     """
18     Translates unicode into closest possible ascii chars before
19     slugifying.
20     """
21     from future.builtins import str
22     return django_slugify(unidecode(str(s)))
23
24
25 def unique_slug(manager, slug_field, slug):
26     """
27     Ensure slug is unique for the given manager, appending a digit
28     if it isn't.
29     """
30     i = 0
31     while True:
32         if i > 0:
33             if i > 1:
34                 slug = slug.rsplit("-", 1)[0]
35             slug = "%s-%s" % (slug, i)
36         if not manager.filter(**{slug_field: slug}):
37             break
38         i += 1
39     return slug
40
41
42 def split_choices(choices_string):
43     """
44     Convert a comma separated choices string to a list.
45     """
46     return [x.strip() for x in choices_string.split(",") if x.strip()]
47
48
49 def html5_field(name, base):
50     """
51     Takes a Django form field class and returns a subclass of
52     it with the given name as its input type.
53     """
54     return type(str(""), (base,), {"input_type": name})
55
56
57 def import_attr(path):
58     """
59     Given a a Python dotted path to a variable in a module,
60     imports the module and returns the variable in it.
61     """
62     module_path, attr_name = path.rsplit(".", 1)
63     return getattr(import_module(module_path), attr_name)