django-object-actions


Namedjango-object-actions JSON
Version 4.2.0 PyPI version JSON
download
home_pagehttps://github.com/crccheck/django-object-actions
SummaryA Django app for adding object tools for models in the admin
upload_time2023-09-08 22:38:55
maintainer
docs_urlNone
authorcrccheck
requires_python>=3.7,<4.0
licenseApache-2.0
keywords django admin
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Django Object Actions

[![CI](https://github.com/crccheck/django-object-actions/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/crccheck/django-object-actions/actions/workflows/ci.yml?query=branch%3Amaster)

If you've ever tried making admin object tools you may have thought, "why can't
this be as easy as making Django Admin Actions?" Well now they can be.

## Quick-Start Guide

Install Django Object Actions:

```shell
$ pip install django-object-actions
```

Add `django_object_actions` to your `INSTALLED_APPS` so Django can find
our templates.

In your admin.py:

```python
from django_object_actions import DjangoObjectActions, action

class ArticleAdmin(DjangoObjectActions, admin.ModelAdmin):
    @action(label="Publish", description="Submit this article") # optional
    def publish_this(self, request, obj):
        publish_obj(obj)

    change_actions = ('publish_this', )
    changelist_actions = ('...', )
```

## Usage

Defining new &_tool actions_ is just like defining regular [admin actions]. The
major difference is the functions for `django-object-actions` will take an
object instance instead of a queryset (see _Re-using Admin Actions_ below).

_Tool actions_ are exposed by putting them in a `change_actions` attribute in
your `admin.ModelAdmin`. You can also add _tool actions_ to the main changelist
views too. There, you'll get a queryset like a regular [admin action][admin actions]:

```python
from django_object_actions import DjangoObjectActions

class MyModelAdmin(DjangoObjectActions, admin.ModelAdmin):
    @action(
        label="This will be the label of the button",  # optional
        description="This will be the tooltip of the button" # optional
    )
    def toolfunc(self, request, obj):
        pass

    def make_published(modeladmin, request, queryset):
        queryset.update(status='p')

    change_actions = ('toolfunc', )
    changelist_actions = ('make_published', )
```

Just like admin actions, you can send a message with `self.message_user`.
Normally, you would do something to the object and return to the same url, but
if you return a `HttpResponse`, it will follow it (hey, just like [admin
actions]!).

If your admin modifies `get_urls`, `change_view`, or `changelist_view`,
you'll need to take extra care because `django-object-actions` uses them too.

### Re-using Admin Actions

If you would like a preexisting admin action to also be an _object action_, add
the `takes_instance_or_queryset` decorator to convert object instances into a
queryset and pass querysets:

```python
from django_object_actions import DjangoObjectActions, takes_instance_or_queryset

class RobotAdmin(DjangoObjectActions, admin.ModelAdmin):
    # ... snip ...

    @takes_instance_or_queryset
    def tighten_lug_nuts(self, request, queryset):
        queryset.update(lugnuts=F('lugnuts') - 1)

    change_actions = ['tighten_lug_nuts']
    actions = ['tighten_lug_nuts']
```

[admin actions]: https://docs.djangoproject.com/en/stable/ref/contrib/admin/actions/

### Customizing _Object Actions_

To give the action some a helpful title tooltip, you can use the `action` decorator
and set the description argument.

```python
@action(description="Increment the vote count by one")
def increment_vote(self, request, obj):
    obj.votes = obj.votes + 1
    obj.save()
```

Alternatively, you can also add a `short_description` attribute,
similar to how admin actions work:

```python
def increment_vote(self, request, obj):
    obj.votes = obj.votes + 1
    obj.save()
increment_vote.short_description = "Increment the vote count by one"
```

By default, Django Object Actions will guess what to label the button
based on the name of the function. You can override this with a `label`
attribute:

```python
@action(label="Vote++")
def increment_vote(self, request, obj):
    obj.votes = obj.votes + 1
    obj.save()
```

or

```python
def increment_vote(self, request, obj):
    obj.votes = obj.votes + 1
    obj.save()
increment_vote.label = "Vote++"
```

If you need even more control, you can add arbitrary attributes to the buttons
by adding a Django widget style
[attrs](https://docs.djangoproject.com/en/stable/ref/forms/widgets/#django.forms.Widget.attrs)
attribute:

```python
@action(attrs = {'class': 'addlink'})
def increment_vote(self, request, obj):
    obj.votes = obj.votes + 1
    obj.save()
```

or

```python
def increment_vote(self, request, obj):
    obj.votes = obj.votes + 1
    obj.save()
increment_vote.attrs = {
    'class': 'addlink',
}
```

### Programmatically Disabling Actions

You can programmatically disable registered actions by defining your own
custom `get_change_actions()` method. In this example, certain actions
only apply to certain object states (e.g. You should not be able to
close an company account if the account is already closed):

```python
def get_change_actions(self, request, object_id, form_url):
    actions = super(PollAdmin, self).get_change_actions(request, object_id, form_url)
    actions = list(actions)
    if not request.user.is_superuser:
        return []

    obj = self.model.objects.get(pk=object_id)
    if obj.question.endswith('?'):
        actions.remove('question_mark')

    return actions
```

The same is true for changelist actions with `get_changelist_actions`.

### Alternate Installation

You don't have to add this to `INSTALLED_APPS`, all you need to to do
is copy the template `django_object_actions/change_form.html` some place
Django's template loader [will find
it](https://docs.djangoproject.com/en/stable/ref/settings/#template-dirs).

If you don't intend to use the template customizations at all, don't
add `django_object_actions` to your `INSTALLED_APPS` at all and use
`BaseDjangoObjectActions` instead of `DjangoObjectActions`.

## More Examples

Making an action that links off-site:

```python
def external_link(self, request, obj):
    from django.http import HttpResponseRedirect
    return HttpResponseRedirect(f'https://example.com/{obj.id}')
```

## Limitations

1.  `django-object-actions` expects functions to be methods of the model
    admin. While Django gives you a lot more options for their admin
    actions.
2.  If you provide your own custom `change_form.html`, you'll also need
    to manually copy in the relevant bits of [our change form
    ](./django_object_actions/templates/django_object_actions/change_form.html).
3.  Security. This has been written with the assumption that everyone in
    the Django admin belongs there. Permissions should be enforced in
    your own actions irregardless of what this provides. Better default
    security is planned for the future.

## Python and Django compatibility

See [`ci.yml`](./.github/workflows/ci.yml) for which Python and Django versions this supports.

## Demo Admin & Docker images

You can try the demo admin against several versions of Django with these Docker
images: https://hub.docker.com/r/crccheck/django-object-actions/tags

This runs the example Django project in `./example_project` based on the "polls"
tutorial. `admin.py` demos what you can do with this app.

## Development

Getting started:

```shell
# get a copy of the code
git clone git@github.com:crccheck/django-object-actions.git
cd django-object-actions
# Install requirements
make install
make test  # run test suite
make quickstart  # runs 'make resetdb' and some extra steps
```

Various helpers are available as make commands. Type `make help` and
view the `Makefile` to see what other things you can do.

Some commands assume you are in the virtualenv. If you see
"ModuleNotFoundError"s, try running `poetry shell` first.

## Similar Packages

If you want an actions menu for each row of your changelist, check out [Django
Admin Row Actions](https://github.com/DjangoAdminHackers/django-admin-row-actions).

Django Object Actions is very similar to
[django-object-tools](https://github.com/praekelt/django-object-tools), but does
not require messing with your urls.py, does not do anything special with
permissions, and uses the same patterns as making [admin actions].


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/crccheck/django-object-actions",
    "name": "django-object-actions",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7,<4.0",
    "maintainer_email": "",
    "keywords": "django,admin",
    "author": "crccheck",
    "author_email": "c@crccheck.com",
    "download_url": "https://files.pythonhosted.org/packages/da/5c/c22183feb3397ccfaaac5c199c329fa6952a90934d792962eab4e5f94eea/django_object_actions-4.2.0.tar.gz",
    "platform": null,
    "description": "# Django Object Actions\n\n[![CI](https://github.com/crccheck/django-object-actions/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/crccheck/django-object-actions/actions/workflows/ci.yml?query=branch%3Amaster)\n\nIf you've ever tried making admin object tools you may have thought, \"why can't\nthis be as easy as making Django Admin Actions?\" Well now they can be.\n\n## Quick-Start Guide\n\nInstall Django Object Actions:\n\n```shell\n$ pip install django-object-actions\n```\n\nAdd `django_object_actions` to your `INSTALLED_APPS` so Django can find\nour templates.\n\nIn your admin.py:\n\n```python\nfrom django_object_actions import DjangoObjectActions, action\n\nclass ArticleAdmin(DjangoObjectActions, admin.ModelAdmin):\n    @action(label=\"Publish\", description=\"Submit this article\") # optional\n    def publish_this(self, request, obj):\n        publish_obj(obj)\n\n    change_actions = ('publish_this', )\n    changelist_actions = ('...', )\n```\n\n## Usage\n\nDefining new &_tool actions_ is just like defining regular [admin actions]. The\nmajor difference is the functions for `django-object-actions` will take an\nobject instance instead of a queryset (see _Re-using Admin Actions_ below).\n\n_Tool actions_ are exposed by putting them in a `change_actions` attribute in\nyour `admin.ModelAdmin`. You can also add _tool actions_ to the main changelist\nviews too. There, you'll get a queryset like a regular [admin action][admin actions]:\n\n```python\nfrom django_object_actions import DjangoObjectActions\n\nclass MyModelAdmin(DjangoObjectActions, admin.ModelAdmin):\n    @action(\n        label=\"This will be the label of the button\",  # optional\n        description=\"This will be the tooltip of the button\" # optional\n    )\n    def toolfunc(self, request, obj):\n        pass\n\n    def make_published(modeladmin, request, queryset):\n        queryset.update(status='p')\n\n    change_actions = ('toolfunc', )\n    changelist_actions = ('make_published', )\n```\n\nJust like admin actions, you can send a message with `self.message_user`.\nNormally, you would do something to the object and return to the same url, but\nif you return a `HttpResponse`, it will follow it (hey, just like [admin\nactions]!).\n\nIf your admin modifies `get_urls`, `change_view`, or `changelist_view`,\nyou'll need to take extra care because `django-object-actions` uses them too.\n\n### Re-using Admin Actions\n\nIf you would like a preexisting admin action to also be an _object action_, add\nthe `takes_instance_or_queryset` decorator to convert object instances into a\nqueryset and pass querysets:\n\n```python\nfrom django_object_actions import DjangoObjectActions, takes_instance_or_queryset\n\nclass RobotAdmin(DjangoObjectActions, admin.ModelAdmin):\n    # ... snip ...\n\n    @takes_instance_or_queryset\n    def tighten_lug_nuts(self, request, queryset):\n        queryset.update(lugnuts=F('lugnuts') - 1)\n\n    change_actions = ['tighten_lug_nuts']\n    actions = ['tighten_lug_nuts']\n```\n\n[admin actions]: https://docs.djangoproject.com/en/stable/ref/contrib/admin/actions/\n\n### Customizing _Object Actions_\n\nTo give the action some a helpful title tooltip, you can use the `action` decorator\nand set the description argument.\n\n```python\n@action(description=\"Increment the vote count by one\")\ndef increment_vote(self, request, obj):\n    obj.votes = obj.votes + 1\n    obj.save()\n```\n\nAlternatively, you can also add a `short_description` attribute,\nsimilar to how admin actions work:\n\n```python\ndef increment_vote(self, request, obj):\n    obj.votes = obj.votes + 1\n    obj.save()\nincrement_vote.short_description = \"Increment the vote count by one\"\n```\n\nBy default, Django Object Actions will guess what to label the button\nbased on the name of the function. You can override this with a `label`\nattribute:\n\n```python\n@action(label=\"Vote++\")\ndef increment_vote(self, request, obj):\n    obj.votes = obj.votes + 1\n    obj.save()\n```\n\nor\n\n```python\ndef increment_vote(self, request, obj):\n    obj.votes = obj.votes + 1\n    obj.save()\nincrement_vote.label = \"Vote++\"\n```\n\nIf you need even more control, you can add arbitrary attributes to the buttons\nby adding a Django widget style\n[attrs](https://docs.djangoproject.com/en/stable/ref/forms/widgets/#django.forms.Widget.attrs)\nattribute:\n\n```python\n@action(attrs = {'class': 'addlink'})\ndef increment_vote(self, request, obj):\n    obj.votes = obj.votes + 1\n    obj.save()\n```\n\nor\n\n```python\ndef increment_vote(self, request, obj):\n    obj.votes = obj.votes + 1\n    obj.save()\nincrement_vote.attrs = {\n    'class': 'addlink',\n}\n```\n\n### Programmatically Disabling Actions\n\nYou can programmatically disable registered actions by defining your own\ncustom `get_change_actions()` method. In this example, certain actions\nonly apply to certain object states (e.g. You should not be able to\nclose an company account if the account is already closed):\n\n```python\ndef get_change_actions(self, request, object_id, form_url):\n    actions = super(PollAdmin, self).get_change_actions(request, object_id, form_url)\n    actions = list(actions)\n    if not request.user.is_superuser:\n        return []\n\n    obj = self.model.objects.get(pk=object_id)\n    if obj.question.endswith('?'):\n        actions.remove('question_mark')\n\n    return actions\n```\n\nThe same is true for changelist actions with `get_changelist_actions`.\n\n### Alternate Installation\n\nYou don't have to add this to `INSTALLED_APPS`, all you need to to do\nis copy the template `django_object_actions/change_form.html` some place\nDjango's template loader [will find\nit](https://docs.djangoproject.com/en/stable/ref/settings/#template-dirs).\n\nIf you don't intend to use the template customizations at all, don't\nadd `django_object_actions` to your `INSTALLED_APPS` at all and use\n`BaseDjangoObjectActions` instead of `DjangoObjectActions`.\n\n## More Examples\n\nMaking an action that links off-site:\n\n```python\ndef external_link(self, request, obj):\n    from django.http import HttpResponseRedirect\n    return HttpResponseRedirect(f'https://example.com/{obj.id}')\n```\n\n## Limitations\n\n1.  `django-object-actions` expects functions to be methods of the model\n    admin. While Django gives you a lot more options for their admin\n    actions.\n2.  If you provide your own custom `change_form.html`, you'll also need\n    to manually copy in the relevant bits of [our change form\n    ](./django_object_actions/templates/django_object_actions/change_form.html).\n3.  Security. This has been written with the assumption that everyone in\n    the Django admin belongs there. Permissions should be enforced in\n    your own actions irregardless of what this provides. Better default\n    security is planned for the future.\n\n## Python and Django compatibility\n\nSee [`ci.yml`](./.github/workflows/ci.yml) for which Python and Django versions this supports.\n\n## Demo Admin & Docker images\n\nYou can try the demo admin against several versions of Django with these Docker\nimages: https://hub.docker.com/r/crccheck/django-object-actions/tags\n\nThis runs the example Django project in `./example_project` based on the \"polls\"\ntutorial. `admin.py` demos what you can do with this app.\n\n## Development\n\nGetting started:\n\n```shell\n# get a copy of the code\ngit clone git@github.com:crccheck/django-object-actions.git\ncd django-object-actions\n# Install requirements\nmake install\nmake test  # run test suite\nmake quickstart  # runs 'make resetdb' and some extra steps\n```\n\nVarious helpers are available as make commands. Type `make help` and\nview the `Makefile` to see what other things you can do.\n\nSome commands assume you are in the virtualenv. If you see\n\"ModuleNotFoundError\"s, try running `poetry shell` first.\n\n## Similar Packages\n\nIf you want an actions menu for each row of your changelist, check out [Django\nAdmin Row Actions](https://github.com/DjangoAdminHackers/django-admin-row-actions).\n\nDjango Object Actions is very similar to\n[django-object-tools](https://github.com/praekelt/django-object-tools), but does\nnot require messing with your urls.py, does not do anything special with\npermissions, and uses the same patterns as making [admin actions].\n\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "A Django app for adding object tools for models in the admin",
    "version": "4.2.0",
    "project_urls": {
        "Homepage": "https://github.com/crccheck/django-object-actions",
        "Repository": "https://github.com/crccheck/django-object-actions"
    },
    "split_keywords": [
        "django",
        "admin"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "eac71c6f42d39b1ec64ea5266effca823cf28beb441fd9c829de72c9fce30dcb",
                "md5": "a5b40ad4c34a579c7e18ecbef121e551",
                "sha256": "ae0df9984c68a4f42f219a391b71fa0630fe44a2983b39b8064378ebddcff30c"
            },
            "downloads": -1,
            "filename": "django_object_actions-4.2.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "a5b40ad4c34a579c7e18ecbef121e551",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7,<4.0",
            "size": 18397,
            "upload_time": "2023-09-08T22:38:54",
            "upload_time_iso_8601": "2023-09-08T22:38:54.321612Z",
            "url": "https://files.pythonhosted.org/packages/ea/c7/1c6f42d39b1ec64ea5266effca823cf28beb441fd9c829de72c9fce30dcb/django_object_actions-4.2.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "da5cc22183feb3397ccfaaac5c199c329fa6952a90934d792962eab4e5f94eea",
                "md5": "42bf194dd0a64cd3a9189da896fb8973",
                "sha256": "e24befedf01b6fcdccbb03c33c0e2c855fd1a88f352a66dc7e2170ba31e80128"
            },
            "downloads": -1,
            "filename": "django_object_actions-4.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "42bf194dd0a64cd3a9189da896fb8973",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7,<4.0",
            "size": 17320,
            "upload_time": "2023-09-08T22:38:55",
            "upload_time_iso_8601": "2023-09-08T22:38:55.486900Z",
            "url": "https://files.pythonhosted.org/packages/da/5c/c22183feb3397ccfaaac5c199c329fa6952a90934d792962eab4e5f94eea/django_object_actions-4.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-09-08 22:38:55",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "crccheck",
    "github_project": "django-object-actions",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "django-object-actions"
}
        
Elapsed time: 0.18156s