Michele Rava
Michele Rava

Reputation: 304

How to call custom method in django's admin template

I've got a trouble: I can easily update my html template sending the "object_list" object and iterating it with 

{%for item in object_list%}
#... some operation
{% endfor %}

However I don't know yet to do the same with my overriden admin-template in "template/admin/add_form.html": how to send and retrieve a method I added to my admin.py ModelAdmin custom class?

here there's my url.py

from django.urls import path
from django.conf.urls import url
from . import views as mysearch_views

from django.contrib import admin
from django.views.generic import ListView, DetailView
from .models import MySearch

# Admin custom
admin.sites.AdminSite.site_header = ‘to be decided’
admin.sites.AdminSite.site_title = ‘to be decided’
admin.sites.AdminSite.index_title = ‘to be decided’

urlpatterns = [
url(r'^$', mysearch_views.my_search, name="my_search"),
url(r'^(?P<id>\d+)/(?P<slug>[\w-]+)/$', DetailView.as_view(model=MySearch, template_name="queries.html"), name="queries"),
url(r'^contacts', mysearch_views.contacts, name="contacts"),
url(r'^result-table', mysearch_views.create_table, name="results"),]

Thanks in advance

Upvotes: 0

Views: 2099

Answers (1)

evergreen
evergreen

Reputation: 886

In your ModelAdmin class, you can override the add_view method to add custom context data for the Add Form. There are other methods for other admin views: change_view for the Change Form, etc.

def add_view(self, request, form_url='', extra_context=None):
    extra_context = extra_context or {}
    extra_context['your_custom_data'] = self.your_custom_method()
    return super().add_view(request, form_url, extra_context=extra_context)

You can then use {{ your_custom_data }} in your overridden admin template.

add_view and the other related methods are documented here.

Upvotes: 2

Related Questions