Skip to content

Commit 702d642

Browse files
committed
Move utils into utils
1 parent 19c36f7 commit 702d642

File tree

2 files changed

+21
-6
lines changed

2 files changed

+21
-6
lines changed

forms_builder/forms/fields.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
from django.core.exceptions import ImproperlyConfigured
44
from django import forms
55
from django.forms.extras import SelectDateWidget
6-
from django.utils.importlib import import_module
76
from django.utils.translation import ugettext_lazy as _
87

98
from forms_builder.forms.settings import USE_HTML5, EXTRA_FIELDS, EXTRA_WIDGETS
9+
from forms_builder.forms.utils import html5_field, import_attr
1010

1111

1212
# Constants for all available field types.
@@ -80,7 +80,6 @@
8080
MULTIPLE = (CHECKBOX_MULTIPLE, SELECT_MULTIPLE)
8181

8282
# HTML5 Widgets
83-
html5_field = lambda name, base: type(str(""), (base,), {"input_type": name})
8483
if USE_HTML5:
8584
WIDGETS.update({
8685
DATE: html5_field("date", forms.DateInput),
@@ -96,11 +95,9 @@
9695
if field_id in CLASSES:
9796
err = "ID %s for field %s in FORMS_EXTRA_FIELDS already exists"
9897
raise ImproperlyConfigured(err % (field_id, field_name))
99-
module_path, member_name = field_path.rsplit(".", 1)
100-
CLASSES[field_id] = getattr(import_module(module_path), member_name)
98+
CLASSES[field_id] = import_attr(field_path)
10199
NAMES += ((field_id, _(field_name)),)
102100

103101
# Add/update custom widgets.
104102
for field_id, widget_path in EXTRA_WIDGETS:
105-
module_path, member_name = widget_path.rsplit(".", 1)
106-
WIDGETS[field_id] = getattr(import_module(module_path), member_name)
103+
WIDGETS[field_id] = import_attr(widget_path)

forms_builder/forms/utils.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from future.builtins import str
33

44
from django.template.defaultfilters import slugify as django_slugify
5+
from django.utils.importlib import import_module
56
from unidecode import unidecode
67

78

@@ -43,3 +44,20 @@ def split_choices(choices_string):
4344
Convert a comma separated choices string to a list.
4445
"""
4546
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)

0 commit comments

Comments
 (0)