Skip to main content

A Django app for adding object tools for models in the admin

Project description

Django Object Actions

CI

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:

$ pip install django-object-actions

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

In your admin.py:

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', )

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:

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:

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']

Customizing Object Actions

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

@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:

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:

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

or

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 attribute:

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

or

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

Adding inline forms

You can add parameters to the action button by adding Django Form object to it. Parameter values can be read form request's POST property.

from django import forms

class ResetAllForm(forms.Form):
    new_value = forms.IntegerField(initial=0)

def reset_all(self, request, queryset):
    new_value = int(request.POST["new_value"])
    queryset.update(value=new_value)
reset_all.form = ResetAllForm()

Each action with form assigned is rendered in it's own, separate row.

Alternatively you can set form_in_modal=True property, which will open a form on a separate page. This is recommended for complex forms.

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):

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.

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:

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 .
  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 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:

# 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.

Django Object Actions is very similar to 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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

skytek_django_object_actions-5.2.0.tar.gz (18.9 kB view details)

Uploaded Source

Built Distribution

File details

Details for the file skytek_django_object_actions-5.2.0.tar.gz.

File metadata

  • Download URL: skytek_django_object_actions-5.2.0.tar.gz
  • Upload date:
  • Size: 18.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.9.6 readme-renderer/42.0 requests/2.31.0 requests-toolbelt/1.0.0 urllib3/2.1.0 tqdm/4.66.1 importlib-metadata/6.8.0 keyring/24.3.0 rfc3986/2.0.0 colorama/0.4.6 CPython/3.10.13

File hashes

Hashes for skytek_django_object_actions-5.2.0.tar.gz
Algorithm Hash digest
SHA256 68d02c924f40112da572b5a76f40f061ed35acfb61f208a31d758edd59214693
MD5 a684173e6f2bba562bba4d60e00e4c6f
BLAKE2b-256 654cefb64c31f142931a207c375f4ca2114a02f237d8090ec152085acaca1bce

See more details on using hashes here.

File details

Details for the file skytek_django_object_actions-5.2.0-py3-none-any.whl.

File metadata

  • Download URL: skytek_django_object_actions-5.2.0-py3-none-any.whl
  • Upload date:
  • Size: 20.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.9.6 readme-renderer/42.0 requests/2.31.0 requests-toolbelt/1.0.0 urllib3/2.1.0 tqdm/4.66.1 importlib-metadata/6.8.0 keyring/24.3.0 rfc3986/2.0.0 colorama/0.4.6 CPython/3.10.13

File hashes

Hashes for skytek_django_object_actions-5.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 24d0b3cab727815ea0472657aced8ec1b4080bccd0057e3dce48477431e71ee2
MD5 3c8b84b20ab418d89cee717991629e16
BLAKE2b-256 7b5e619b654ce2638543e834160e7e740d9f43fd09f0f831493fa7840c6015b3

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page