[Answered ]-Triggering Custom Functionality in Django Admin

2👍

step1: First override the change_list.html which is at /app/templates/admin/app/change_list.html.(if it’s not there create one)

The contents of change_list.html will look like

{% block object-tools %}
    {% if has_add_permission %}
        <ul class="grp-object-tools">
            {% block object-tools-items %}
                <li><a href="export/" class="grp-state-focus">
                    Export Data
                </a></li>
                <li><a href="add/{% if is_popup %}?_popup=1{% endif %}" class="grp-add-link grp-state-focus">
                    {% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}
                </a></li>
            {% endblock %}
        </ul>
    {% endif %}
{% endblock %}

step2: In admin.py for this form add get_urls method

def get_urls(self):
    urls = super(classname, self).get_urls() # replace wit your class name
    my_urls = patterns(
        '',
        url(r'^export/$',
            ExportCampaignView.as_view(), name='export'),
    )
    return my_urls + urls

step3: In views.py add this logic to download the file

XLSX_CONTENT_TYPE = ('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

class ExportCampaignView(generic.View):

    def get(self, request, *args, **kwargs):
        xlsx_file = self.create_xlsx()
        response = HttpResponse(xlsx_file, content_type=XLSX_CONTENT_TYPE)
        response['Content-Disposition'] = (
            'attachment; filename=campaign.xlsx')
        return response

    @staticmethod
    def create_xlsx():
        """
        :return tablib.Dataset: Campaign data.
        """
        output = StringIO()
        workbook = xlsxwriter.Workbook(output)
        sheet = workbook.add_worksheet()
        bold_with_bg = workbook.add_format(
            {'bold': True, 'bg_color': 'silver'})
        date_format = workbook.add_format({'num_format': 'dd.mm.YYYY'})

        headers = [
            _(u'col1'), _(u'col2'), _(u'col3'),

        ]


        data = Model.objects.all()

        for row_idx, row in enumerate(data, start=1):
            sheet.write(row_idx, 0, row.col1)
            sheet.write(row_idx, 1, row.col2)
            sheet.write(row_idx, 1, row.col3)

        workbook.close()
        output.seek(0)
        return output
👤Pavan

Leave a comment