Skip to content

Add AdminMixin #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,6 @@ dmypy.json

# sqlite
test.db
*.sqlite3

tests/testapp/migrations/
68 changes: 62 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,68 @@ ConcurrentTransitionMixin to cause a rollback of all the changes that
have been executed in an inconsistent (out of sync) state, thus
practically negating their effect.

## Admin Integration

1. Make sure `django_fsm` is in your `INSTALLED_APPS` settings:

``` python
INSTALLED_APPS = (
...
'django_fsm',
...
)
```

NB: If you're migrating from [django-fsm-admin](https://github.com/gadventures/django-fsm-admin) (or any alternative), make sure it's not installed anymore to avoid installing the old django-fsm.


2. In your admin.py file, use FSMAdminMixin to add behaviour to your ModelAdmin. FSMAdminMixin should be before ModelAdmin, the order is important.

``` python
from django_fsm.admin import FSMAdminMixin

@admin.register(AdminBlogPost)
class MyAdmin(FSMAdminMixin, admin.ModelAdmin):
fsm_field = ['my_fsm_field']
...
```

3. You can customize the label by adding ``custom={"label": "My awesome transition"}`` to the transition decorator

``` python
@transition(
field='state',
source=['startstate'],
target='finalstate',
custom={"label": False},
)
def do_something(self, param):
...
```

4. By adding ``custom={"admin": False}`` to the transition decorator, one can disallow a transition to show up in the admin interface.

``` python
@transition(
field='state',
source=['startstate'],
target='finalstate',
custom={"admin": False},
)
def do_something(self, param):
# will not add a button "Do Something" to your admin model interface
```

By adding `FSM_ADMIN_FORCE_PERMIT = True` to your configuration settings (or `default_disallow_transition = False` to your admin), the above restriction becomes the default.
Then one must explicitly allow that a transition method shows up in the admin interface.

``` python
@admin.register(AdminBlogPost)
class MyAdmin(FSMAdminMixin, admin.ModelAdmin):
default_disallow_transition = False
...
```

## Drawing transitions

Renders a graphical overview of your models states transitions
Expand Down Expand Up @@ -436,12 +498,6 @@ $ ./manage.py graph_transitions -e transition_1,transition_2 myapp.Blog

## Extensions

You may also take a look at django-fsm-2-admin project containing a mixin
and template tags to integrate django-fsm-2 state transitions into the
django admin.

<https://github.com/coral-li/django-fsm-2-admin>

Transition logging support could be achieved with help of django-fsm-log
package

Expand Down
181 changes: 181 additions & 0 deletions django_fsm/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
from __future__ import annotations

from dataclasses import dataclass
from functools import partial
from typing import Any

from django.conf import settings
from django.contrib import messages
from django.contrib.admin.options import BaseModelAdmin
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
from django.core.exceptions import FieldDoesNotExist
from django.http import HttpRequest
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.utils.translation import gettext_lazy as _

import django_fsm as fsm

try:
import django_fsm_log # noqa: F401
except ModuleNotFoundError:
FSM_LOG_ENABLED = False

Check warning on line 22 in django_fsm/admin.py

View check run for this annotation

Codecov / codecov/patch

django_fsm/admin.py#L21-L22

Added lines #L21 - L22 were not covered by tests
else:
FSM_LOG_ENABLED = True


@dataclass
class FSMObjectTransition:
fsm_field: str
block_label: str
available_transitions: list[fsm.Transition]


class FSMAdminMixin(BaseModelAdmin):
change_form_template: str = "django_fsm/fsm_admin_change_form.html"

fsm_fields: list[str] = []
fsm_transition_success_msg = _("FSM transition '{transition_name}' succeeded.")
fsm_transition_error_msg = _("FSM transition '{transition_name}' failed: {error}.")
fsm_transition_not_allowed_msg = _("FSM transition '{transition_name}' is not allowed.")
fsm_transition_not_valid_msg = _("FSM transition '{transition_name}' is not a valid.")
fsm_context_key = "fsm_object_transitions"
fsm_post_param = "_fsm_transition_to"
default_disallow_transition = not getattr(settings, "FSM_ADMIN_FORCE_PERMIT", False)

def get_fsm_field_instance(self, fsm_field_name: str) -> fsm.FSMField | None:
try:
return self.model._meta.get_field(fsm_field_name)
except FieldDoesNotExist:
return None

def get_readonly_fields(self, request: HttpRequest, obj: Any = None) -> tuple[str]:
read_only_fields = super().get_readonly_fields(request, obj)

for fsm_field_name in self.fsm_fields:
if fsm_field_name in read_only_fields:
continue

Check warning on line 57 in django_fsm/admin.py

View check run for this annotation

Codecov / codecov/patch

django_fsm/admin.py#L57

Added line #L57 was not covered by tests
field = self.get_fsm_field_instance(fsm_field_name=fsm_field_name)
if field and getattr(field, "protected", False):
read_only_fields += (fsm_field_name,)

return read_only_fields

@staticmethod
def get_fsm_block_label(fsm_field_name: str) -> str:
return f"Transition ({fsm_field_name})"

def get_fsm_object_transitions(self, request: HttpRequest, obj: Any) -> list[FSMObjectTransition]:
fsm_object_transitions = []

for field_name in sorted(self.fsm_fields):
if func := getattr(obj, f"get_available_user_{field_name}_transitions"):
fsm_object_transitions.append( # noqa: PERF401
FSMObjectTransition(
fsm_field=field_name,
block_label=self.get_fsm_block_label(fsm_field_name=field_name),
available_transitions=[
t for t in func(user=request.user) if t.custom.get("admin", self.default_disallow_transition)
],
)
)

return fsm_object_transitions

def change_view(
self,
request: HttpRequest,
object_id: str,
form_url: str = "",
extra_context: dict[str, Any] | None = None,
) -> HttpResponse:
_context = extra_context or {}
_context[self.fsm_context_key] = self.get_fsm_object_transitions(
request=request,
obj=self.get_object(request=request, object_id=object_id),
)

return super().change_view(
request=request,
object_id=object_id,
form_url=form_url,
extra_context=_context,
)

def get_fsm_redirect_url(self, request: HttpRequest, obj: Any) -> str:
return request.path

def get_fsm_response(self, request: HttpRequest, obj: Any) -> HttpResponse:
redirect_url = self.get_fsm_redirect_url(request=request, obj=obj)
redirect_url = add_preserved_filters(
context={
"preserved_filters": self.get_preserved_filters(request),
"opts": self.model._meta,
},
url=redirect_url,
)
return HttpResponseRedirect(redirect_to=redirect_url)

def response_change(self, request: HttpRequest, obj: Any) -> HttpResponse:
if self.fsm_post_param in request.POST:
try:
transition_name = request.POST[self.fsm_post_param]
transition_func = getattr(obj, transition_name)
except AttributeError:
self.message_user(
request=request,
message=self.fsm_transition_not_valid_msg.format(
transition_name=transition_name,
),
level=messages.ERROR,
)
return self.get_fsm_response(
request=request,
obj=obj,
)

try:
if FSM_LOG_ENABLED:
for fn in [
partial(transition_func, request=request, by=request.user),
partial(transition_func, by=request.user),
transition_func,
]:
try:
fn()
except TypeError: # noqa: PERF203
pass
else:
break
else:
transition_func()

Check warning on line 151 in django_fsm/admin.py

View check run for this annotation

Codecov / codecov/patch

django_fsm/admin.py#L151

Added line #L151 was not covered by tests
except fsm.TransitionNotAllowed:
self.message_user(
request=request,
message=self.fsm_transition_not_allowed_msg.format(
transition_name=transition_name,
),
level=messages.ERROR,
)
except fsm.ConcurrentTransition as err:
self.message_user(
request=request,
message=self.fsm_transition_error_msg.format(transition_name=transition_name, error=str(err)),
level=messages.ERROR,
)
else:
obj.save()
self.message_user(
request=request,
message=self.fsm_transition_success_msg.format(
transition_name=transition_name,
),
level=messages.INFO,
)

return self.get_fsm_response(
request=request,
obj=obj,
)

return super().response_change(request=request, obj=obj)

Check warning on line 181 in django_fsm/admin.py

View check run for this annotation

Codecov / codecov/patch

django_fsm/admin.py#L181

Added line #L181 was not covered by tests
15 changes: 15 additions & 0 deletions django_fsm/templates/django_fsm/fsm_admin_change_form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{% extends 'admin/change_form.html' %}

{% block submit_buttons_bottom %}

{% for fsm_object_transition in fsm_object_transitions %}
<div class="submit-row">
<label>{{ fsm_object_transition.block_label }}</label>
{% for transition in fsm_object_transition.available_transitions %}
<input type="submit" value="{{ transition.custom.label|default:transition.name }}" name="_fsm_transition_to">
{% endfor %}
</div>
{% endfor %}

{{ block.super }}
{% endblock %}
50 changes: 49 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ pre-commit = "*"
pytest = "*"
pytest-cov = "*"
pytest-django = "*"
django_fsm_log = "*"

[tool.pytest.ini_options]
DJANGO_SETTINGS_MODULE = "tests.settings"
Expand Down
33 changes: 33 additions & 0 deletions tests/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django_fsm_log",
"guardian",
*PROJECT_APPS,
]
Expand Down Expand Up @@ -135,3 +136,35 @@
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"


# Django FSM-log settings
DJANGO_FSM_LOG_IGNORED_MODELS = (
# "tests.testapp.models.AdminBlogPost",
"tests.testapp.models.Application",
"tests.testapp.models.BlogPost",
"tests.testapp.models.DbState",
"tests.testapp.models.FKApplication",
"tests.testapp.tests.SimpleBlogPost",
"tests.testapp.tests.test_abstract_inheritance.BaseAbstractModel",
"tests.testapp.tests.test_abstract_inheritance.InheritedFromAbstractModel",
"tests.testapp.tests.test_access_deferred_fsm_field.DeferrableModel",
"tests.testapp.tests.test_basic_transitions.SimpleBlogPost",
"tests.testapp.tests.test_conditions.BlogPostWithConditions",
"tests.testapp.tests.test_custom_data.BlogPostWithCustomData",
"tests.testapp.tests.test_exception_transitions.ExceptionalBlogPost",
"tests.testapp.tests.test_graph_transitions.VisualBlogPost",
"tests.testapp.tests.test_integer_field.BlogPostWithIntegerField",
"tests.testapp.tests.test_lock_mixin.ExtendedBlogPost",
"tests.testapp.tests.test_lock_mixin.LockedBlogPost",
"tests.testapp.tests.test_mixin_support.MixinSupportTestModel",
"tests.testapp.tests.test_multi_resultstate.MultiResultTest",
"tests.testapp.tests.test_multidecorators.MultiDecoratedModel",
"tests.testapp.tests.test_protected_field.ProtectedAccessModel",
"tests.testapp.tests.test_protected_fields.RefreshableProtectedAccessModel",
"tests.testapp.tests.test_proxy_inheritance.InheritedModel",
"tests.testapp.tests.test_state_transitions.Caterpillar",
"tests.testapp.tests.test_string_field_parameter.BlogPostWithStringField",
"tests.testapp.tests.test_transition_all_except_target.ExceptTargetTransition",
"tests.testapp.tests.test_key_field.FKBlogPost",
)
Loading