Content¶
Content plugins are presentational plugins, that make your forms look more
- Dummy: Mainly for dev purposes.
- Content image: Insert an image.
- Content text: Add text.
- Content video: Add an embed YouTube or Vimeo video.
django-fobi (later on named just fobi) is a customisable, modular, user- and developer- friendly form builder application for Django. With fobi you can build Django forms using an intiutive GUI, save or mail posted form data. API allows you to build your own form elements and form handlers (mechanisms for handling the submitted form data).
Note, that Django 1.7 is not yet proclaimed to be flawlessly supported!
Note, that Fobi does not require django-admin and administrative rights/ permissions to access the UI, although almost seamless integration with django-admin is implemented through the simple theme.
Some of the upcoming/in-development features/improvements are:
See the TODOS for the full list of planned-, pending- in-development- or to-be-implemented features.
$ pip install django-fobi
Or latest stable version from GitHub:
$ pip install -e git+https://github.com/barseghyanartur/django-fobi@stable#egg=django-fobi
Or latest stable version from BitBucket:
$ pip install -e hg+https://bitbucket.org/barseghyanartur/django-fobi@stable#egg=django-fobi
INSTALLED_APPS = (
# ...
# Fobi core
'fobi',
# Fobi themes
'fobi.contrib.themes.bootstrap3', # Bootstrap 3 theme
'fobi.contrib.themes.foundation5', # Foundation 5 theme
'fobi.contrib.themes.simple', # Simple theme
# Fobi form elements - fields
'fobi.contrib.plugins.form_elements.fields.boolean',
'fobi.contrib.plugins.form_elements.fields.date',
'fobi.contrib.plugins.form_elements.fields.datetime',
'fobi.contrib.plugins.form_elements.fields.email',
'fobi.contrib.plugins.form_elements.fields.file',
'fobi.contrib.plugins.form_elements.fields.hidden',
'fobi.contrib.plugins.form_elements.fields.integer',
'fobi.contrib.plugins.form_elements.fields.password',
'fobi.contrib.plugins.form_elements.fields.radio',
'fobi.contrib.plugins.form_elements.fields.select',
'fobi.contrib.plugins.form_elements.fields.select_model_object',
'fobi.contrib.plugins.form_elements.fields.select_multiple',
'fobi.contrib.plugins.form_elements.fields.text',
'fobi.contrib.plugins.form_elements.fields.textarea',
'fobi.contrib.plugins.form_elements.fields.url',
# Fobi form elements - content elements
'fobi.contrib.plugins.form_elements.content.dummy',
'fobi.contrib.plugins.form_elements.content.image',
'fobi.contrib.plugins.form_elements.content.text',
'fobi.contrib.plugins.form_elements.content.video',
# Form handlers
'fobi.contrib.plugins.form_handlers.db_store',
'fobi.contrib.plugins.form_handlers.http_repost',
'fobi.contrib.plugins.form_handlers.mail',
# Other project specific apps
'foo', # Test app
# ...
)
And the following to the context processors.
TEMPLATE_CONTEXT_PROCESSORS = (
# ...
"fobi.context_processors.theme".
# ...
)
Make sure that django.core.context_processors.request is in TEMPLATE_CONTEXT_PROCESSORS too.
Add the following line to urlpatterns of your urls module.
# View URLs
url(r'^fobi/', include('fobi.urls.view')),
# Edit URLs
url(r'^fobi/', include('fobi.urls.edit')),
View URLs are put separately from edit URLs in order to make it possible to prefix the edit URLs differently. For example, if you’re using the “Simple” theme, you would likely want to prefix the edit URLs with “admin/” so that it looks more like django-admin.
See the documentation for some screen shots:
In order to be able to quickly evaluate the Fobi, a demo app (with a quick installer) has been created (works on Ubuntu/Debian, may work on other Linux systems as well, although not guaranteed). Follow the instructions below for having the demo running within a minute.
Grab the latest django_fobi_example_app_installer.sh:
$ wget https://raw.github.com/barseghyanartur/django-fobi/stable/examples/django_fobi_example_app_installer.sh
Assign execute rights to the installer and run the django_fobi_example_app_installer.sh:
$ chmod +x django_fobi_example_app_installer.sh
$ ./django_fobi_example_app_installer.sh
Open your browser and test the app.
Dashboard:
Django admin interface:
If quick installer doesn’t work for you, see the manual steps on running the example project.
Form element plugins represent the elements of which the forms is made: Inputs, checkboxes, textareas, files, hidden fields, as well as pure presentational elements (text or image). Number of form elements in a form is not limited.
Presentational form elements are inherited from fobi.base.FormElementPlugin.
The rest (real form elements, that are supposed to have a value) are inherited from fobi.base.FormFieldPlugin.
You should see a form element plugin as a Django micro app, which could have its’ own models, admin interface, etc.
Fobi comes with several bundled form element plugins. Do check the source code as example.
Let’s say, you want to create a textarea form element plugin.
There are several properties, each textarea should have. They are:
Let’s name that plugin sample_textarea. The plugin directory should then have the following structure.
path/to/sample_textarea/
├── __init__.py
├── fobi_form_elements.py # Where plugins are defined and registered
├── forms.py # Plugin configuration form
└── widgets.py # Where plugins widgets are defined
Form element plugins should be registered in “fobi_form_elements.py” file. Each plugin module should be put into the INSTALLED_APPS of your Django projects’ settings.
In some cases, you would need plugin specific overridable settings (see fobi.contrib.form_elements.fields.content.image plugin as an example). You are advised to write your settings in such a way, that variables of your Django project settings module would have FOBI_PLUGIN_ prefix.
Step by step review of a how to create and register a plugin and plugin widgets. Note, that Fobi autodiscovers your plugins if you place them into a file named fobi_form_elements.py of any Django app listed in INSTALLED_APPS of your Django projects’ settings module.
A single form element plugin is registered by its’ UID.
Required imports.
from django import forms
from fobi.base import FormFieldPlugin, form_element_plugin_registry
from path.to.sample_textarea.forms import SampleTextareaForm
Defining the Sample textarea plugin.
class SampleTextareaPlugin(FormFieldPlugin):
uid = "sample_textarea"
name = "Sample Textarea"
form = SampleTextareaForm
group = "Samples" # Group to which the plugin belongs to
def get_form_field_instances(self):
kwargs = {
'required': self.data.required,
'label': self.data.label,
'initial': self.data.initial,
'widget': forms.widgets.Textarea(attrs={})
}
return [(self.data.name, forms.CharField, kwargs),]
Registering the SampleTextareaPlugin plugin.
form_element_plugin_registry.register(SampleTextareaPlugin)
Note, that in case you want to define a pure presentational element, make use of fobi.base.FormElementPlugin for subclassing, instead of fobi.base.FormFieldPlugin. See the source of the content plugins (fobi.contrib.plugins.form_elements.content) as a an example.
There might be cases, when you need to do additional handling of the data upon the successful form submittion. In such cases, you will need to define a submit_plugin_form_data method in the plugin, which accepts the following arguments:
Example (taken from fobi.contrib.plugins.form_elements.fields.file):
def submit_plugin_form_data(self, form_entry, request, form):
# Get the file path
file_path = form.cleaned_data.get(self.data.name, None)
if file_path:
# Handle the upload
saved_file = handle_uploaded_file(FILES_UPLOAD_DIR, file_path)
# Overwrite ``cleaned_data`` of the ``form`` with path to moved
# file.
form.cleaned_data[self.data.name] = "{0}{1}".format(
settings.MEDIA_URL, saved_file
)
# It's critically important to return the ``form`` with updated
# ``cleaned_data``
return form
In the example below, the original form is being modified. If you don’t want the original form to be modified, do not return anything.
Check the file form element plugin (fobi.contrib.plugins.form_elements.fields.file) for complete example.
Why to have another file for defining forms? Just to keep the code clean and less messy, although you could perfectly define all your plugin forms in the module fobi_form_elements.py, it’s recommended to keep it separate.
Take into consideration, that forms.py is not an autodiscovered file pattern. All your form element plugins should be registered in modules named fobi_form_elements.py.
Required imports.
from django import forms
from fobi.base import BasePluginForm
Form for for SampleTextareaPlugin form element plugin.
class SampleTextareaForm(forms.Form, BasePluginForm):
plugin_data_fields = [
("name", ""),
("label", ""),
("initial", ""),
("required", False)
]
name = forms.CharField(label="Name", required=True)
label = forms.CharField(label="Label", required=True)
initial = forms.CharField(label="Initial", required=False)
required = forms.BooleanField(label="Required", required=False)
Note that although it’s not being checked in the code, but for form field plugins the following fields should be present in the plugin form (BasePluginForm) and the form plugin (FormFieldPlugin):
In some cases, you might want to do something with the data before it gets saved. For that purpose, save_plugin_data method has been introduced.
See the following example.
def save_plugin_data(self, request=None):
"""
Saving the plugin data and moving the file.
"""
file_path = self.cleaned_data.get('file', None)
if file_path:
saved_image = handle_uploaded_file(IMAGES_UPLOAD_DIR, file_path)
self.cleaned_data['file'] = saved_image
Required imports.
from fobi.base import FormElementPluginWidget
Defining the base plugin widget.
class BaseSampleTextareaPluginWidget(FormElementPluginWidget):
# Same as ``uid`` value of the ``SampleTextareaPlugin``.
plugin_uid = "sample_textarea"
Register in the registry (in some module which is for sure to be loaded; it’s handy to do it in the theme module).
Required imports.
from fobi.base import form_element_plugin_widget_registry
from path.to.sample_textarea.widgets import BaseSampleTextareaPluginWidget
Define the theme specific plugin.
class SampleTextareaPluginWidget(BaseSampleTextareaPluginWidget):
theme_uid = 'bootstrap3' # Theme for which the widget is loaded
media_js = ['sample_layout/js/fobi.plugins.form_elements.sample_textarea.js',]
media_css = ['sample_layout/css/fobi.plugins.form_elements.sample_textarea.css',]
Register the widget.
form_element_plugin_widget_registry.register(SampleTextareaPluginWidget)
Now, that everything is ready, make sure your plugin module is added to INSTALLED_APPS.
INSTALLED_APPS = (
# ...
'path.to.sample_textarea',
# ...
)
Afterwards, go to terminal and type the following command.
$ ./manage.py fobi_sync_plugins
If your HTTP server is running, you would then be able to see the new plugin in the edit form interface.
Dashboard URL: http://127.0.0.1:8000/fobi/
Note, that you have to be logged in, in order to use the dashboard. If your new plugin doesn’t appear, set the FOBI_DEBUG to True in your Django’s local settings module, re-run your code and check console for error notifications.
Form handler plugins handle the form data. Fobi comes with several bundled form handler plugins, among which is the db_store and mail plugins, which are responsible for saving the submitted form data into the database and mailing the data to recipients specified. Number of form handlers in a form is not limited. Certain form handlers are not configurable (for example the db_store form handler isn’t), while others are (mail, http_repost).
You should see a form handler as a Django micro app, which could have its’ own models, admin interface, etc.
As said above, Fobi comes with several bundled form handler plugins. Do check the source code as example.
Let’s name that plugin sample_mail. The plugin directory should then have the following structure.
path/to/sample_mail/
├── __init__.py
├── fobi_form_handlers.py # Where plugins are defined and registered
└── forms.py # Plugin configuration form
Form handler plugins should be registered in “fobi_form_handlers.py” file. Each plugin module should be put into the INSTALLED_APPS of your Django projects’ settings.
A single form handler plugin is registered by its’ UID.
Required imports.
import json
from django.core.mail import send_mail
from fobi.base import FormHandlerPlugin, form_handler_plugin_registry
from path.to.sample_mail.forms import SampleMailForm
Defining the Sample mail handler plugin.
class SampleMailHandlerPlugin(FormHandlerPlugin):
uid = "sample_mail"
name = _("Sample mail")
form = SampleMailForm
def run(self, form_entry, request, form):
send_mail(
self.data.subject,
json.dumps(form.cleaned_data),
self.data.from_email,
[self.data.to_email],
fail_silently = True
)
Some form handlers are configurable, some others not. In order to have a user friendly way of showing the form handler settings, what’s sometimes needed, a plugin_data_repr method has been introducd. Simplest implementation of it would look as follows:
def plugin_data_repr(self):
"""
Human readable representation of plugin data.
:return string:
"""
return self.data.__dict__
If plugin is configurable, it has configuration data. A single form may have unlimited number of same plugins. Imagine, you want to have different subjects and additional body texts for different user groups. You could then assign two form handler mail plugins to the form. Of course, saving the posted form data many times does not make sense, but it’s up to the user. So, in case if plugin is configurable, it should have a form.
Why to have another file for defining forms? Just to keep the code clean and less messy, although you could perfectly define all your plugin forms in the module fobi_form_handlers.py, it’s recommended to keep it separate.
Take into consideration, that forms.py is not an autodiscovered file pattern. All your form handler plugins should be registered in modules named fobi_form_handlers.py.
Required imports.
from django import forms
from django.utils.translation import ugettext_lazy as _
from fobi.base import BasePluginForm
Defining the form for Sample mail handler plugin.
class MailForm(forms.Form, BasePluginForm):
plugin_data_fields = [
("from_name", ""),
("from_email", ""),
("to_name", ""),
("to_email", ""),
("subject", ""),
("body", ""),
]
from_name = forms.CharField(label=_("From name"), required=True)
from_email = forms.EmailField(label=_("From email"), required=True)
to_name = forms.CharField(label=_("To name"), required=True)
to_email = forms.EmailField(label=_("To email"), required=True)
subject = forms.CharField(label=_("Subject"), required=True)
body = forms.CharField(label=_("Body"), required = False,
widget=forms.widgets.Textarea)
After the plugin has been processed, all its’ data is available in a plugin_instance.data container (for example, plugin_instance.data.subject or plugin_instance.data.from_name).
Some form handlers shall be executed prior others. A good example of such, is a combination of “mail” and “db_save” form handlers for the form. In case of large files posted, submittion of form data would fail if “mail” plugin would be executed after “db_save” has been executed. That’s why it’s possible to prioritise that ordering in a FOBI_FORM_HANDLER_PLUGINS_EXECUTION_ORDER setting variable.
If not specified or left empty, form handler plugins would be ran in the order of discovery. All form handler plugins that are not listed in the FORM_HANDLER_PLUGINS_EXECUTION_ORDER, would be ran after the plugins that are mentioned there.
FORM_HANDLER_PLUGINS_EXECUTION_ORDER = (
'http_repost',
'mail',
# The 'db_store' is left out intentionally, since it should
# be the last plugin to be executed.
)
By default, a single form handler plugin has at least a “delete” action. If plugin is configurable, it gets an “edit” action as well.
For some of your plugins, you may want to register a custom action. For example, the “db_store” plugin does have one, for showing a link to a listing page with saved form data for the form given.
For such cases, define a custom_actions method in your form handler plugin. That method shall return a list of triples. In each triple, first value is the URL, second value is the title and the third value is the icon of the URL.
The following example is taken from the “db_store” plugin.
def custom_actions(self):
"""
Adding a link to view the saved form enties.
:return iterable:
"""
return (
(
reverse('fobi.contrib.plugins.form_handlers.db_store.view_saved_form_data_entries'),
_("View entries"),
'glyphicon glyphicon-list'
),
)
Do not forget to add the form handler plugin module to INSTALLED_APPS.
INSTALLED_APPS = (
# ...
'path.to.sample_mail',
# ...
)
Afterwards, go to terminal and type the following command.
$ ./manage.py fobi_sync_plugins
If your HTTP server is running, you would then be able to see the new plugin in the edit form interface.
Form callbacks are additional hooks, that are executed on various stages of the form submission.
Let’s place the callback in the foo module. The plugin directory should then have the following structure.
path/to/foo/
├── __init__.py
└── fobi_form_callbacks.py # Where callbacks are defined and registered
See the callback example below.
Required imports.
from fobi.constants import (
CALLBACK_BEFORE_FORM_VALIDATION,
CALLBACK_FORM_VALID_BEFORE_SUBMIT_PLUGIN_FORM_DATA,
CALLBACK_FORM_VALID, CALLBACK_FORM_VALID_AFTER_FORM_HANDLERS,
CALLBACK_FORM_INVALID
)
from fobi.base import FormCallback, form_callback_registry
Define and register the callback
class SampleFooCallback(FormCallback):
stage = CALLBACK_FORM_VALID
def callback(self, form_entry, request, form):
print("Great! Your form is valid!")
form_callback_registry.register(SampleFooCallback)
Add the callback module to INSTALLED_APPS.
INSTALLED_APPS = (
# ...
'path.to.foo',
# ...
)
Sometimes, you would want to specify a different action for the form. Although it’s possible to define a custom form action (action field in the “Form properties” tab), you’re advised to use the http_repost plugin instead, since then the form would be still validated locally and only then the valid data, as is, would be sent to the desired endpoint.
Take in mind, that if both cases, if CSRF protection is enabled on the endpoint, your post request would result an error.
Fobi, with its’ flexible form elements, form handlers and form callbacks is very customisable. However, there might be cases when you need to override entire view to fit your needs. Take a look at the FeinCMS integration as a good example of such. You may also want to compare the code from original view fobi.views.view_form_entry with the code from the widget to get a better idea of what could be changed in your case. If need a good advice, just ask me.
Fobi comes with theming API. While there are several ready-to-use themes:
Have in mind, that creating a brand new theme could be time consuming. Instead, you are advised to extend existing themes or in the worst case, if too much customisation required, create your own themes based on existing ones (just copy the desired theme to your project directory and work it out further).
It’s possible to use different templates for all “view” and “edit” actions (see the source code of the “simple” theme). Both Bootstrap 3 and Foundation 5 themes look great. Although if you can’t use any of those, the “simple” theme is the best start, since it looks just like django-admin.
Let’s place the theme in the sample_theme module. The theme directory should then have the following structure.
path/to/sample_theme/
├── static
│ ├── css
│ │ └── sample_theme.css
│ └── js
│ └── sample_theme.js
├── templates
│ └── sample_theme
│ ├── _base.html
│ ├── add_form_element_entry.html
│ ├── ...
│ └── view_form_entry_ajax.html
├── __init__.py
├── fobi_form_elements.py
└── fobi_themes.py # Where themes are defined and registered
See the theme example below.
from django.utils.translation import ugettext_lazy as _
from fobi.base import BaseTheme, theme_registry
class SampleTheme(BaseTheme):
"""
Sample theme.
"""
uid = 'sample'
name = _("Sample")
media_css = (
'sample_theme/css/sample_theme.css',
'css/fobi.core.css',
)
media_js = (
'js/jquery-1.10.2.min.js',
'jquery-ui/js/jquery-ui-1.10.3.custom.min.js',
'js/jquery.slugify.js',
'js/fobi.core.js',
'sample_theme/js/sample_theme.js',
)
# Form element specific
form_element_html_class = 'form-control'
form_radio_element_html_class = 'radio'
form_element_checkbox_html_class = 'checkbox'
form_edit_form_entry_option_class = 'glyphicon glyphicon-edit'
form_delete_form_entry_option_class = 'glyphicon glyphicon-remove'
form_list_container_class = 'list-inline'
# Templates
master_base_template = 'sample_theme/_base.html'
base_template = 'sample_theme/base.html'
form_ajax = 'sample_theme/snippets/form_ajax.html'
form_snippet_template_name = 'sample_theme/snippets/form_snippet.html'
form_properties_snippet_template_name = 'sample_theme/snippets/form_properties_snippet.html'
messages_snippet_template_name = 'sample_theme/snippets/messages_snippet.html'
add_form_element_entry_template = 'sample_theme/add_form_element_entry.html'
add_form_element_entry_ajax_template = 'sample_theme/add_form_element_entry_ajax.html'
add_form_handler_entry_template = 'sample_theme/add_form_handler_entry.html'
add_form_handler_entry_ajax_template = 'sample_theme/add_form_handler_entry_ajax.html'
create_form_entry_template = 'sample_theme/create_form_entry.html'
create_form_entry_ajax_template = 'bootstrap3/create_form_entry_ajax.html'
dashboard_template = 'sample_theme/dashboard.html'
edit_form_element_entry_template = 'sample_theme/edit_form_element_entry.html'
edit_form_element_entry_ajax_template = 'sample_theme/edit_form_element_entry_ajax.html'
edit_form_entry_template = 'sample_theme/edit_form_entry.html'
edit_form_entry_ajax_template = 'sample_theme/edit_form_entry_ajax.html'
edit_form_handler_entry_template = 'sample_theme/edit_form_handler_entry.html'
edit_form_handler_entry_ajax_template = 'sample_theme/edit_form_handler_entry_ajax.html'
form_entry_submitted_template = 'sample_theme/form_entry_submitted.html'
form_entry_submitted_ajax_template = 'sample_theme/form_entry_submitted_ajax.html'
view_form_entry_template = 'sample_theme/view_form_entry.html'
view_form_entry_ajax_template = 'sample_theme/view_form_entry_ajax.html'
Registering the SampleTheme plugin.
theme_registry.register(SampleTheme)
Sometimes you would want to attach additional properties to the theme in order to use them later in templates (rememeber, current theme object is always available in templates under name fobi_theme).
For such cases you would need to define a variable in your project’s settings module, called FOBI_CUSTOM_THEME_DATA. See the following code as example:
# Fobi custom theme data for to be displayed in third party apps
# like `django-registraton`.
FOBI_CUSTOM_THEME_DATA = {
'bootstrap3': {
'page_header_html_class': '',
'form_html_class': 'form-horizontal',
'form_button_outer_wrapper_html_class': 'control-group',
'form_button_wrapper_html_class': 'controls',
'form_button_html_class': 'btn',
'form_primary_button_html_class': 'btn-primary pull-right',
},
'foundation5': {
'page_header_html_class': '',
'form_html_class': 'form-horizontal',
'form_button_outer_wrapper_html_class': 'control-group',
'form_button_wrapper_html_class': 'controls',
'form_button_html_class': 'radius button',
'form_primary_button_html_class': 'btn-primary',
},
'simple': {
'page_header_html_class': '',
'form_html_class': 'form-horizontal',
'form_button_outer_wrapper_html_class': 'control-group',
'form_button_wrapper_html_class': 'submit-row',
'form_button_html_class': 'btn',
'form_primary_button_html_class': 'btn-primary',
}
}
You would now be able to access the defined extra properties in templates as shown below.
<div class="{{ fobi_theme.custom_data.form_button_wrapper_html_class }}">
You likely would want to either remove the footer text or change it. Define a variable in your project’s settings module, called FOBI_THEME_FOOTER_TEXT. See the following code as example:
FOBI_THEME_FOOTER_TEXT = gettext('© django-fobi example site 2014')
Below follow the properties of the theme:
There are generic templates made in order to simplify theming. Some of them you would never need to override. Some others, you would likely want to.
Templates that you likely would want to re-write in your custom theme implemention are marked with three asterics (***):
generic
├── snippets
│ ├── form_ajax.html
│ ├── form_edit_ajax.html
│ ├── *** form_properties_snippet.html
│ ├── *** form_snippet.html
│ ├── --- form_edit_snippet.html (does not exist in generic templates)
│ ├── --- form_view_snippet.html (does not exist in generic templates)
│ ├── form_view_ajax.html
│ └── messages_snippet.html
│
├── _base.html
├── add_form_element_entry.html
├── add_form_element_entry_ajax.html
├── add_form_handler_entry.html
├── add_form_handler_entry_ajax.html
├── base.html
├── create_form_entry.html
├── create_form_entry_ajax.html
├── *** dashboard.html
├── edit_form_element_entry.html
├── edit_form_element_entry_ajax.html
├── edit_form_entry.html
├── *** edit_form_entry_ajax.html
├── edit_form_handler_entry.html
├── edit_form_handler_entry_ajax.html
├── form_entry_submitted.html
├── *** form_entry_submitted_ajax.html
├── *** theme.html
├── view_form_entry.html
└── view_form_entry_ajax.html
From all of the templates listed above, the _base.html template is the most influenced by the Bootstrap 3 theme.
As said above, making your own theme from scratch could be costy. Instead, you can override/reuse an existing one and change it to your needs with minimal efforts. See the override simple theme example. In order to see it in action, run the project with settings_override_simple_theme option:
./manage.py runserver --settings=settings_override_simple_theme
Details explained below.
override_simple_theme/
├── static
│ └── override_simple_theme
│ ├── css
│ │ └── override-simple-theme.css
│ └── js
│ └── override-simple-theme.js
│
├── templates
│ └── override_simple_theme
│ ├── snippets
│ │ └── form_ajax.html
│ └── base_view.html
├── __init__.py
└── fobi_themes.py # Where themes are defined and registered
Overriding the “simple” theme.
__all__ = ('MySimpleTheme',)
from fobi.base import theme_registry
from fobi.contrib.themes.simple.fobi_themes import SimpleTheme
class MySimpleTheme(SimpleTheme):
html_classes = ['my-simple-theme',]
base_view_template = 'override_simple_theme/base_view.html'
form_ajax = 'override_simple_theme/snippets/form_ajax.html'
Register the overridden theme. Note, that it’s important to set the force argument to True, in order to override the original theme. Force can be applied only once (for a overridden element).
theme_registry.register(MySimpleTheme, force=True)
{% extends "simple/base_view.html" %}
{% load static %}
{% block stylesheets %}
<link
href="{% static 'override_simple_theme/css/override-simple-theme.css' %}"
rel="stylesheet" media="all" />
{% endblock stylesheets %}
{% block main-wrapper %}
<div id="sidebar">
<h2>It's easy to override a theme!</h2>
</div>
{{ block.super }}
{% endblock main-wrapper %}
{% extends "fobi/generic/snippets/form_ajax.html" %}
{% block form_html_class %}basic-grey{% endblock %}
Plugin system allows administrators to specify the access rights to every plugin. Fobi permissions are based on Django Users and User Groups. Access rights are managable via Django admin (“/admin/fobi/formelement/”, “/admin/fobi/formhandler/”). If user doesn’t have the rights to access plugin, it doesn’t appear on his form even if has been added to it (imagine, you have once granted the right to use the news plugin to all users, but later on decided to limit it to Staff members group only). Note, that superusers have access to all plugins.
Plugin access rights management interface in Django admin
┌──────────────────────────────┬───────────────────────┬───────────────────────┐
│ `Plugin` │ `Users` │ `Groups` │
├──────────────────────────────┼───────────────────────┼───────────────────────┤
│ Text │ John Doe │ Form builder users │
├──────────────────────────────┼───────────────────────┼───────────────────────┤
│ Textarea │ │ Form builder users │
├──────────────────────────────┼───────────────────────┼───────────────────────┤
│ File │ Oscar, John Doe │ Staff members │
├──────────────────────────────┼───────────────────────┼───────────────────────┤
│ URL │ │ Form builder users │
├──────────────────────────────┼───────────────────────┼───────────────────────┤
│ Hidden │ │ Form builder users │
└──────────────────────────────┴───────────────────────┴───────────────────────┘
There are several management commands available.
There are number of Dash settings you can override in the settings module of your Django project:
For tuning of specific contrib plugin, see the docs in the plugin directory.
Fobi ships with number of bundled form element- and form handler- plugins, as well as themes which are ready to be used as is.
Below a short overview of the form element plugins. See the README.rst file in directory of each plugin for details.
Content plugins are presentational plugins, that make your forms look more
Below a short overview of the form handler plugins. See the README.rst file in directory of each plugin for details.
Below a short overview of the themes. See the README.rst file in directory of each theme for details.
The following HTML5 fields are supported in appropriate bundled plugins:
With the fobi.contrib.plugins.form_elements.fields.input support for HTML5 fields is extended to the following fields:
By default debugging is turned off. It means that broken form entries, which are entries with broken data, that are not possible to be shown, are just skipped. That’s safe in production. Although, you for sure would want to see the broken entries in development. Set the FOBI_DEBUG to True in the settings.py of your project in order to do so.
Most of the errors are logged (DEBUG). If you have written a plugin and it somehow doesn’t appear in the list of available plugins, do run the ./manage.py fobi_sync_plugins management command since it not only syncs your plugins into the database, but also is a great way of checking for possible errors.
If you have forms refering to form element- of form handler- plugins that are currently missing (not registered, removed, failed to load - thus there would be a risk that your form would’t be rendered properly/fully and the necessary data handling wouldn’t happen either) you will get an appropriate exception. Although it’s fine to get an instant error message about such failures in development, in production is wouldn’t look appropriate. Thus, there are two settings related to the non-existing (not-found) form element- and form handler- plugins.
If you get a FormElementPluginDoesNotExist or a FormHandlerPluginDoesNotExist exception, make sure you have listed your plugin in the settings module of your project.
GPL 2.0/LGPL 2.1
For any issues contact me at the e-mail given in the Author section.
Artur Barseghyan <artur.barseghyan@gmail.com>
Contents:
Get a setting from fobi.contrib.apps.feincms_integration conf module, falling back to the default.
If override is not None, it will be used instead of the setting.
Parameters: |
|
---|---|
Returns: | Setting value. |
Bases: fobi.base.FormElementPlugin
Dummy plugin.
Bases: fobi.base.FormElementPluginWidget
Base dummy form element plugin widget.
Get a setting from fobi.contrib.plugins.form_elements.content.image conf module, falling back to the default.
If override is not None, it will be used instead of the setting.
Parameters: |
|
---|---|
Returns: | Setting value. |
Parameters: | image_file (django.core.files.uploadedfile.InMemoryUploadedFile) – |
---|---|
Return string: | Path to the image (relative). |
Delete file from disc.
Get a setting from fobi.contrib.plugins.form_elements.content.video conf module, falling back to the default.
If override is not None, it will be used instead of the setting.
Parameters: |
|
---|---|
Returns: | Setting value. |
Get a setting from fobi.contrib.plugins.form_elements.fields.conf module, falling back to the default.
If override is not None, it will be used instead of the setting.
Parameters: |
|
---|---|
Returns: | Setting value. |
Get a setting from fobi.contrib.plugins.form_elements.fields.select_model_object conf module, falling back to the default.
If override is not None, it will be used instead of the setting.
Parameters: |
|
---|---|
Returns: | Setting value. |
Bases: django.apps.config.AppConfig
Get a setting from fobi.contrib.plugins.form_elements.fields.select_multiple_model_objects conf module, falling back to the default.
If override is not None, it will be used instead of the setting.
Parameters: |
|
---|---|
Returns: | Setting value. |
Bases: django.contrib.admin.options.ModelAdmin
Saved form data entry admin.
Get a setting from fobi.contrib.plugins.form_elements.content.image conf module, falling back to the default.
If override is not None, it will be used instead of the setting.
Parameters: |
|
---|---|
Returns: | Setting value. |
Bases: fobi.base.FormHandlerPlugin
Adding a link to view the saved form enties.
Return iterable: | |
---|---|
Parameters: |
|
---|
Bases: django.db.models.base.Model
Saved form data.
Bases: django.core.exceptions.ObjectDoesNotExist
Bases: django.core.exceptions.MultipleObjectsReturned
Shows the formatted saved data records.
Return string: |
---|
View saved form data entries.
Parameters: |
|
---|---|
Return django.http.HttpResponse: | |
Bases: fobi.contrib.plugins.form_elements.content.dummy.widgets.BaseDummyPluginWidget
Dummy plugin widget for Boootstrap 3.
Bases: fobi.base.BaseTheme
Bootstrap3 theme.
Bases: fobi.base.BaseTheme
Foundation5 theme. Based on the “Workspace” example of the Foundation 5. Click here for more.
Bases: fobi.base.BaseTheme
Simple theme that has a native Django style.
Gets the plugin. Note, that entry shall be a instance of fobi.models.FormElementEntry or fobi.models.FormHandlerEntry.
Syntax: | {% get_fobi_plugin entry as [context_var_name] %} |
---|---|
Example: | {% get_fobi_plugin entry as plugin %} {% get_fobi_plugin entry as plugin %} {{ plugin.render }} |
Gets the form handler plugin custom actions. Note, that plugin shall be a instance of fobi.models.FormHandlerEntry.
Syntax: | {% get_fobi_form_handler_plugin_custom_actions [plugin] [form_entry] as [context_var_name] %} |
---|---|
Example: | {% get_fobi_form_handler_plugin_custom_actions plugin form_entry as form_handler_plugin_custom_actions %} |
Outputs the first variable passed that is not False, without escaping.
Outputs nothing if all the passed variables are False.
Sample usage:
{% firstof var1 var2 var3 %}
This is equivalent to:
{% if var1 %}
{{ var1|safe }}
{% elif var2 %}
{{ var2|safe }}
{% elif var3 %}
{{ var3|safe }}
{% endif %}
but obviously much cleaner!
You can also use a literal string as a fallback value in case all passed variables are False:
{% firstof var1 var2 var3 "fallback value" %}
If you want to escape the output, use a filter tag:
{% filter force_escape %}
{% firstof var1 var2 var3 "fallback value" %}
{% endfilter %}
All uids are supposed to be pythonic function names (see PEP http://www.python.org/dev/peps/pep-0008/#function-names).
Bases: fobi.base.BaseDataStorage
Storage for FormField data.
Bases: fobi.base.BaseDataStorage
Storage for FormField data.
Bases: object
Not a form actually. Defined for magic only.
Property iterable plugin_data_fields: | |
---|---|
Fields to get when calling the get_plugin_data method. These field will be JSON serialized. All other fields, even if they are part of the form, won’t be. Make sure all fields are serializable. If some of them aren’t, override the save_plugin_data method and make them serializable there. See fobi.contrib.plugins.form_elements.fields.select.forms as a good example. |
|
Example: | >>> plugin_data_fields = (
>>> ('name', ''),
>>> ('active': False)
>>> )
|
Data that would be saved in the plugin_data field of the fobi.models.FormElementEntry or ``fobi.models.FormHandlerEntry`.` subclassed model.
Parameters: | request (django.http.HttpRequest) – |
---|
Bases: object
Base form field from which every form field should inherit.
Properties: |
|
---|
Used when copying entries. If any objects or files are created by plugin, they should be cloned.
Parameters: | fobi.models.AbstractPluginEntry – Instance of fobi.models.AbstractPluginEntry. |
---|---|
Return string: | JSON dumped string of the cloned plugin data. The returned value would be inserted as is into the fobi.models.AbstractPluginEntry.plugin_data field. |
Used in fobi.views.delete_form_entry and fobi.views.delete_form_handler_entry. Fired automatically, when fobi.models.FormEntry object is about to be deleted. Make use of it if your plugin creates database records or files that are not monitored externally but by dash only.
Get the cloned plugin data and returns it in a JSON dumped format.
Parameters: | update (dict) – |
---|---|
Return string: | JSON dumped string of the cloned plugin data. |
Example: |
>>> def clone_plugin_data(self, dashboard_entry):
>>> cloned_image = clone_file(self.data.image, relative_path=True)
>>> return self.get_cloned_plugin_data(update={'image': cloned_image})
Get the plugin form class. Override this method in your subclassed fobi.base.BasePlugin class when you need your plugin setup to vary depending on the placeholder, workspace, user or request given. By default returns the value of the form attribute defined in your plugin.
Return django.forms.Form|django.forms.ModelForm: | |
---|---|
Subclass of django.forms.Form or django.forms.ModelForm. |
Used fobi.views.add_form_element_entry and fobi.views.add_form_handler_entry view to gets initialised form for object to be created.
Same as get_initialised_create_form but raises django.http.Http404 on errors.
Used in fobi.views.edit_form_element_entry and fobi.views.edit_form_handler_entry views.
Same as get_initialised_edit_form but raises django.http.Http404 on errors.
Fed as initial argument to the plugin form when initialising the instance for adding or editing the plugin. Override in your plugin class if you need customisations.
Get the plugin data and returns it in a JSON dumped format.
Parameters: | update (dict) – |
---|---|
Return string: | JSON dumped string of the cloned plugin data. |
Gets the plugin widget.
Parameters: |
|
---|---|
Return mixed: | Subclass of fobi.base.BasePluginWidget or instance of subclassed fobi.base.BasePluginWidget object. |
A massive work on positioning the plugin and having it to be displayed in a given width is done here. We should be getting the plugin widget for the plugin given and based on its’ properties (static!) as well as on plugin position (which we have from model), we can show the plugin with the exact class.
Loads the plugin data saved in fobi.models.FormElementEntry or fobi.models.FormHandlerEntry. Plugin data is saved in JSON string.
Parameters: | plugin_data (string) – JSON string with plugin data. |
---|
Human readable representation of plugin data. A very basic way would be just:
>>> return self.data.__dict__
Return string: |
---|
Redefine in your subclassed plugin when necessary.
Post process plugin data here (before rendering). This methid is being called after the data has been loaded into the plugin.
Note, that request (django.http.HttpRequest) is available (self.request).
Redefine in your subclassed plugin when necessary.
Pre process plugin data (before rendering). This method is being called before the data has been loaded into the plugin.
Note, that request (django.http.HttpRequest) is available ( self.request).
Renders the plugin HTML.
Parameters: | request (django.http.HttpRequest) – |
---|---|
Return string: |
Used in fobi.management.commands.fobi_update_plugin_data.
Some plugins would contain data fetched from various sources (models, remote data). Since form entries are by definition loaded extremely much, you are advised to store as much data as possible in plugin_data field of fobi.models.FormElementEntry or fobi.models.FormHandlerEntry. Some externally fetched data becomes invalid after some time and needs updating. For that purpose, in case if your plugin needs that, redefine this method in your plugin. If you need your data to be periodically updated, add a cron-job which would run fobi_update_plugin_data management command (see fobi.management.commands.fobi_update_plugin_data module).
Parameters: | or fobi.models.FormHandlerEntry (fobi.models.FormElementEntry) – Instance of fobi.models.FormeHandlerEntry. |
---|---|
Return dict: | Should return a dictionary containing data of fields to be updated. |
Bases: fobi.base.BasePlugin
Base form element plugin.
Property fobi.base.FormElementPluginDataStorage storage: | |
---|---|
Property bool has_value: | |
If set to False, ignored (removed) from the POST when processing the form. |
Gets the instances of form fields, that plugin contains.
Parameters: |
|
---|---|
Return list: | List of Django form field instances. |
Example: |
>>> from django.forms.fields import CharField, IntegerField, TextField
>>> [CharField(max_length=100), IntegerField(), TextField()]
If kwargs_update_func is given, is callable and returns results without failures, return the result. Otherwise - return None.
If return_func is given, is callable and returns results without failures, return the result. Otherwise - return None.
alias of FormElementPluginDataStorage
Submit plugin form data. Called on form submittion (when user actually posts the data to assembed form).
Parameters: |
|
---|
Bases: fobi.base.BasePlugin
Form handler plugin.
Override this method in your form handler if you want to specify custom actions. Note, that expected return value of this method is an iterable with a triple, where the first item is the URL of the action and the second item is the action title and the third item is the icon class of the action.
Example: |
---|
>>> return (
>>> ('/add-to-favorites/',
>>> 'Add to favourites',
>>> 'glyphicon glyphicon-favourties'),
>>> )
Internal method to for obtaining the get_custom_actions.
Custom code should be implemented here.
Parameters: |
|
---|
alias of FormHandlerPluginDataStorage
Bases: object
Base form callback.
Custom callback code should be implemented here.
Parameters: |
|
---|
Bases: object
Registry of dash plugins. It’s essential, that class registered has the uid property.
If fail_on_missing_plugin is set to True, an appropriate exception (plugin_not_found_exception_cls) is raised in cases if plugin cound’t be found in the registry.
Property mixed type: | |
---|---|
Property bool fail_on_missing_plugin: | |
Property fobi.exceptions.DoesNotExist plugin_not_found_exception_cls: | |
Property str plugin_not_found_error_message: | |
Gets the given entry from the registry.
Parameters: | uid (string) – |
---|
:return mixed.
alias of DoesNotExist
Bases: fobi.base.BaseRegistry
Form element plugins registry.
alias of FormElementPluginDoesNotExist
Bases: fobi.base.BaseRegistry
Form handler plugins registry.
alias of FormHandlerPluginDoesNotExist
alias of FormHandlerPlugin
Bases: object
Registry of callbacks. Holds callbacks for stages listed in the fobi.constants.CALLBACK_STAGES.
alias of ClassProperty
Gets a list of registered plugins in a form if tuple (plugin name, plugin description). If not yet autodiscovered, autodiscovers them.
Return list: |
---|
Gets a list of registered plugin uids as a list . If not yet autodiscovered, autodiscovers them.
Return list: |
---|
Gets a list of registered plugins in a form if tuple (plugin name, plugin description). If not yet autodiscovered, autodiscovers them.
Return list: |
---|
Gets a list of registered plugins in a form if tuple (plugin name, plugin description). If not yet autodiscovered, autodiscovers them.
Return list: |
---|
Validates the plugin uid.
Parameters: | plugin_uid (string) – |
---|---|
Return bool: |
Gets a list of registered plugins in a form of tuple (plugin name, plugin description). If not yet autodiscovered, autodiscovers them.
Return list: |
---|
Gets a list of registered plugins in a form of tuple (plugin name, plugin description). If not yet autodiscovered, autodiscovers them.
Return list: |
---|
Validates the plugin uid.
Parameters: | plugin_uid (string) – |
---|---|
Return bool: |
Gets registered form callbacks for the stage given.
Fires callbacks.
Parameters: |
|
---|---|
Return django.forms.Form form: | |
Runs form handlers.
Parameters: |
|
---|
Collects the plugin media for form element entries given.
Parameters: |
|
---|---|
Return dict: | Returns a dict containing the ‘js’ and ‘css’ keys. Correspondent values of those keys are lists containing paths to the CSS and JS media files. |
Gets a list of registered themes in form of tuple (plugin name, plugin description). If not yet autodiscovered, autodiscovers them.
Return list: |
---|
Gets a list of registered themes in a form of tuple (plugin name, plugin description). If not yet autodiscovered, autodiscovers them.
Return list: |
---|
Validates the theme uid.
Parameters: | plugin_uid (string) – |
---|---|
Return bool: |
Bases: fobi.base.BasePluginForm
Base form for form field plugins.
Bases: fobi.base.FormElementPlugin
Form field plugin.
Bases: fobi.base.BasePluginWidgetRegistry
Registry of form element plugins.
alias of FormElementPluginWidget
Bases: fobi.base.BasePluginWidgetRegistry
Registry of form handler plugins.
alias of FormHandlerPluginWidget
Bases: fobi.base.BasePluginWidget
Form element plugin widget.
Get a setting from fobi conf module, falling back to the default.
If override is not None, it will be used instead of the setting.
Parameters: |
|
---|---|
Returns: | Setting value. |
Bases: dict
A dictionary that keeps its keys in the order in which they’re inserted. Very similar to (and partly based on) SortedDict of the Django, but has several additional methods implemented, such as: insert_before_key and insert_after_key.
Inserts the key, value pair before the item with the given index.
Inserts the {key: value} after the target_key.
Parameters: |
|
---|---|
Return bool: |
Inserts the {key: value} before the target_key.
Parameters: |
|
---|---|
Return bool: |
Moves the {key: value} after the given source_key.
Parameters: |
|
---|---|
Return bool: |
Checks for the permissions given based on the strategy chosen.
Parameters: |
|
---|---|
Return bool: | |
Example: |
>>> @login_required
>>> @permissions_required(satisfy='any', perms=[
>>> 'fobi.add_formentry',
>>> 'fobi.change_formentry',
>>> 'fobi.delete_formentry',
>>> 'fobi.add_formelemententry',
>>> 'fobi.change_formelemententry',
>>> 'fobi.delete_formelemententry',
>>> ])
>>> def edit_dashboard(request):
>>> # your code
Example: |
---|
>>> @login_required
>>> @all_permissions_required([
>>> 'fobi.add_formentry',
>>> 'fobi.change_formentry',
>>> 'fobi.delete_formentry',
>>> 'fobi.add_formelemententry',
>>> 'fobi.change_formelemententry',
>>> 'fobi.delete_formelemententry',
>>> ])
>>> def edit_dashboard(request):
>>> # your code
Example: |
---|
>>> @login_required
>>> @any_permission_required([
>>> 'fobi.add_formentry',
>>> 'fobi.change_formentry',
>>> 'fobi.delete_formentry',
>>> 'fobi.add_formelemententry',
>>> 'fobi.change_formelemententry',
>>> 'fobi.delete_formelemententry',
>>> ])
>>> def edit_dashboard(request):
>>> # your code
Assembles a form class by given entry.
Parameters: |
|
---|
Bases: fobi.exceptions.BaseException
Exception raised when developer didn’t configure/write the code properly.
Bases: exceptions.ValueError, fobi.exceptions.BaseException
Raised when an attempt is made to register an item in the registry which does not have a proper type.
Bases: fobi.exceptions.BaseException
Raised when something does not exist.
Bases: fobi.exceptions.DoesNotExist
Raised when no theme with given uid can be found.
Bases: fobi.exceptions.DoesNotExist
Raised when no plugin with given uid can be found.
Bases: fobi.exceptions.PluginDoesNotExist
Raised when no form element plugin with given uid can be found.
Bases: fobi.exceptions.PluginDoesNotExist
Raised when no form handler plugin with given uid can be found.
Bases: fobi.exceptions.ImproperlyConfigured
Raised when no active theme is chosen.
Bases: django.forms.fields.Field
To be used with content elements like text or images, that need to be present, for instance, in between form input elements.
Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any.
For most fields, this will simply be data; FileFields need to handle it a bit differently.
alias of NoneWidget
Bases: object
Base importer.
Bases: fobi.base.BaseRegistry
Form importer plugins registry.
alias of BaseFormImporter
Converts iterable of certain objects to dict.
Parameters: |
|
---|---|
Return dict: |
Takes a form and creates label to field name map.
Parameters: |
|
---|---|
Return dict: |
Removes given keys and values from dictionary.
Parameters: |
|
---|---|
Return dict: |
Takes two dictionaries, assuming one contains a mapping keys to titles and another keys to data. Joins as string and returns wrapped into HTML “p” tag.
Makes sure filenames are never overwritten.
Parameters: | destination (string) – |
---|---|
Return string: |
Parameters: | image_file (django.core.files.uploadedfile.InMemoryUploadedFile) – |
---|---|
Return string: | Path to the image (relative). |
Clones the file.
Parameters: | source_filename (string) – Source filename. |
---|---|
Return string: | Filename of the cloned file. |
Gets registered models as list.
Parameters: | ignore (iterable) – Ignore the following content types (should be in app_label.model format (example auth.User). |
---|---|
Return list: |
Gets an admin change URL for the object given.
Parameters: |
|
---|---|
Return str: |