Imagine an application like JIRA with complex workflow. Building such application needs a support for managing finite state machine.Well, if you are building your application with Django, Django FSM provides you out of the box support for managing finite state machine.
Let’s assume that our application has the following workflow for a Task.
The basic model for a Task is as follows:
Now, let’s see how can we build this using Django FSM.
$ pip install django-fsm
Or, you can install latest git version
$ pip install -e git://github.com/kmmbvnr/django-fsm.git#egg=django-fsm
Define States and State Field in Model
You have to define an FSMState field. On this field, Django FSM will perform transitions.
Define these using FSMField.
We defined FSMState field but we didn’t associate any states to that field. We can do that as follows:
Django FSM provides a decorator called transition. Once you decorate the model method with transition decorator, you can call the model method to perform transition on each object of a model.
Source parameter accepts a list of states or an individual state. You can use * for the source, to allow switching to the target from any state. The field parameter accepts both the string attribute name or the actual field instance.
Changing State of Object
To change the state of an object, call the model method which is decorated with transition decorator.
If start() gets executed successfully without raising any exceptions, state of task object will get updated but it will not be saved into a database. Call save() method to save the object in the database.
Adding Conditions on Transitions
There might be situations wherein you want a check of the certain condition prior to performing the transition. You do so in Django FSM using Conditions parameter of transition decorator. Conditions must be a list of functions taking one argument(model instance). The function/method must return,
A conditioning method can be a normal python function.
or it can be a model method.
Use conditions like this:
Handling Exception in Transition Method
Django FSM provides a way to set a fall-back state in case transition method raises an exception.
Transition decorator has permission parameter that can be used to check permission prior to transition taking place. Permission accepts a permission string, or callable that expects instance and user arguments and returns True if the user can perform the transition.
You can check permission with the
State Transition Diagram
You can generate a state transition diagram based on transition methods.
You need the
pip install graphviz>=0.4library and add
django_fsm to your
Now run following command.
$ ./manage.py graph_transitions -o task_transitions.png myapp.Task
Django FSM has everything that you need to manage finite state machine in your application. In addition to this if want to perform transitions from admin site use Django-FSM-admin. Also, you can maintain transition logs using Django-FSM-log.