4

The built-in actions that come with the Django admin generally display a helpful message after they execute at the top, e.g. saying that a new object was added or what have you.

The docs show how to do it with simple actions that can be represented as methods of the custom ModelAdmin. However, with custom actions that need intermediate pages (covered further down on that same page), I am encouraged to pass the user onto another view. That's great, but it means that I no longer have access to the custom ModelAdmin instance in order to call its message_user() method... Or at least I'm not sure how to get it.

Can you tell me how to get a hold of the current ModelAdmin instance or, if there's a better way, how else to display one of those helpful little messages when I'm done in the other view?

bdeniker
  • 995
  • 1
  • 9
  • 21

2 Answers2

7

To mimic the ModelAdmin.message_user method you only need to do the following:

from django.contrib import messages
messages.info(request, message)

Adding a message is documented here https://docs.djangoproject.com/en/dev/ref/contrib/messages/#adding-a-message and the way ModelAdmin uses it can be seen here: https://code.djangoproject.com/browser/django/trunk/django/contrib/admin/options.py#L691

Claude Vedovini
  • 2,421
  • 21
  • 19
  • The hyperlink to the code reference is broken, I would assume it is referencing this? https://github.com/django/django/blob/4.0/django/contrib/admin/options.py#L1072 – Jonáš Vacek Apr 04 '22 at 10:49
0

Construct a LogEntry and write a custom templatetag to render messages on your intermediat page, for instance:

  LogEntry.objects.log_action(
      user_id=request.user.id,
      content_type_id=ContentType.objects.get_for_model(yourmodel).pk,
      object_id=case.id,
      object_repr=force_unicode(yourmodel),
      action_flag=ADDITION if created else CHANGE)

read more: Django docs (Message Framework)

Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100