adding a message for the user in a custom django admin view

365 Views Asked by At

I have created a custom admin site and there is a view I'd like to be invoked with a custom button. This is my adminSite object:

class MyAdminSite(admin.AdminSite):
    site_header = 'My admin site'

    def get_urls(self):
        from django.urls import path
        urls = super().get_urls()
        urls += [
            path('appname/modelname/<int:pk>', self.admin_view(self.my_view), name='appname_modelname_view'),
        ]
        return urls
    
    def my_view(self, request, pk):
        #do something
        messages.info(request, 'some message')
       

registering the model for which the view is invoked

my_admin = MyAdminSite()

class myModelAdmin(admin.ModelAdmin):
    change_form_template = 'admin/appname/change_form.html'

my_admin.register(myModel, myModelAdmin)

change_form.html:

{% extends "admin/change_form.html" %}
{% load i18n admin_urls %}

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

{% block object-tools-items %}
    <li>
        <a href="{% url opts|admin_urlname:'myview' original.pk %}" class="someclass">Invoke</a>
    </li>
    <li>
        <a href="{% url opts|admin_urlname:'history' original.pk|admin_urlquote %}" class="historylink">{% translate "History" %}</a>
    </li>
    {% if has_absolute_url %}
        <li>
            <a href="{% url 'admin:view_on_site' content_type_id original.pk %}" class="viewsitelink">{% translate "View on site" %}</a>
        </li>
    {% endif %}
{% endblock %}

When I click the "invoke" button, it should reload the the page and display the info message on top. However, the page simply reloads.

How do I make sure that the messages are displayed?

Thank you for your time...

0

There are 0 best solutions below