How to do it...

Admin actions are functions that take three arguments, as follows:

  • The current ModelAdmin value
  • The current HttpRequest value
  • The QuerySet value containing the selected items

Perform the following steps to create a custom admin action to export a spreadsheet:

  1. Create an export_xlsx() function in the admin.py file of the products app, as follows:
# products/admin.py
from copy import copy
from openpyxl import Workbook
from openpyxl.styles import Alignment, NamedStyle, builtins
from openpyxl.styles.numbers import FORMAT_NUMBER
from openpyxl.writer.excel import save_virtual_workbook

from django.http.response import HttpResponse
from django.utils.translation import ugettext_lazy as _
# ... other imports ...

def export_xlsx(modeladmin, request, queryset):
wb = Workbook()
ws = wb.active
ws.title = "Products"

number_alignment = Alignment(horizontal="right")
wb.add_named_style(NamedStyle("Identifier",
alignment=number_alignment,
number_format=FORMAT_NUMBER))
wb.add_named_style(NamedStyle("Normal Wrapped",
alignment=Alignment(
wrap_text=True)))

number_headline_1 = copy(builtins.styles["Headline 1"])
number_headline_1.name = "Number Headline 1"
number_headline_1.alignment = number_alignment
wb.add_named_style(number_headline_1)

class Config():
def __init__(self,
heading,
width=None,
heading_style="Headline 1",
style="Normal Wrapped"):
self.heading = heading
self.width = width
self.heading_style = heading_style
self.style = style

column_config = {
"A": Config("ID",
width=10,
heading_style="Number Headline 1",
style="Identifier"),
"B": Config("Title", width=30),
"C": Config("Description", width=60),
"D": Config("Price ($)",
width=15,
heading_style="Number Headline 1",
style="Currency"),
"E": Config("Preview", width=100, style="Hyperlink"),
}

# Set up column widths, header values and styles
for col, conf in column_config.items():
ws.column_dimensions[col].width = conf.width

column = ws[f"{col}1"]
column.value = conf.heading
column.style = conf.heading_style

# Add products
for obj in queryset.order_by("pk"):
project_photos = obj.productphoto_set.all()[:1]
url = ""
if project_photos:
url = project_photos[0].photo.url

data = [obj.pk, obj.title, obj.description, obj.price, url]
ws.append(data)

row = ws.max_row
for row_cells in ws.iter_cols(min_row=row, max_row=row):
for cell in row_cells:
cell.style = column_config[cell.column].style

mimetype = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
charset = "utf-8"
response = HttpResponse(
content=save_virtual_workbook(wb),
content_type=f"{mimetype}; charset={charset}",
charset=charset)
response["Content-Disposition"] = "attachment; filename=products.xlsx"
return response


export_xlsx.short_description = _("Export XLSX")
  1. Then, add the actions setting to ProductAdmin, as follows:
class ProductAdmin(admin.ModelAdmin): 
    # ... 
    actions = [export_xlsx]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.86.183