Skip to content

Commit

Permalink
Use form factory for custom forms and support simple layouts.
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelkuty committed Mar 23, 2016
1 parent c496279 commit bbad8a8
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 2 deletions.
62 changes: 61 additions & 1 deletion horizon_contrib/forms/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@

try:
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Div
from crispy_forms.layout import Div, Layout
from crispy_forms.bootstrap import Tab, TabHolder
CRISPY = True
except Exception as e:
CRISPY = False
Expand All @@ -30,6 +31,14 @@ class SelfHandlingMixin(object):

"""A base :class:`Form <django:django.forms.Form>` class which includes
processing logic in its subclasses.
tabs = {
'tab1': {
'name': 'Verbose Name'
'fields': ('field_name1',)
}
}
"""
required_css_class = 'required'

Expand Down Expand Up @@ -57,6 +66,57 @@ def __init__(self, request=None, *args, **kwargs):
except Exception:
pass

def init_layout(self):
'''Call init for generic layout'''
self.helper.layout = Layout(TabHolder())
self.init_custom_tabs()

def get_tabs(self):
'''Merge form tabs with models tabs'''
tabs = getattr(self._meta.model, 'tabs', {})
tabs.update(getattr(self, 'tabs', {}))
return tabs

def init_custom_tabs(self):
'''init custom tabs
tabs = {
'tab1': {
'name': 'Verbose Name'
'fields': ('field_name1',)
}
}
'''
for tab_name, tab in self.get_tabs().items():
self.insert_tab(tab.get('name', tab_name), tab['fields'])

def get_main_fields(self, fields):
'''filter field which are included in custom tab'''
_fields = []
for field in fields:
if field not in self._custom_fields():
_fields.append(field)
return _fields

def _custom_fields(self):
'''returns acumulated fields from ``tabs``'''
fields = []
if not hasattr(self, '__custom_fields'):
for tab_name, tab in self.get_tabs().items():
fields += list(tab['fields'])
self.__custom_fields = fields
return self.__custom_fields

def insert_tab(self, name, fields, position=1):
'''Push tab to specific position
in the default state is after main widget tab
'''
self.helper.layout[0].insert(
position,
Tab(name,
*fields
)
)


class SelfHandlingForm(SelfHandlingMixin, django_forms.Form):

Expand Down
3 changes: 2 additions & 1 deletion horizon_contrib/forms/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,8 @@ def get_form_class(self):
# use standard form instead of raising exception
pass
else:
return form_class
return model_forms.modelform_factory(self.model, exclude=[],
form=form_class)

if self.form_class:
return self.form_class
Expand Down

0 comments on commit bbad8a8

Please sign in to comment.