56. Export CSV of site

In this section, we will implement the functionality to export report data as a CSV file.

First, weโ€™ll define the export_csv function within the utility.py file. This function will generate a CSV file based on the userโ€™s selected report and return it as an HTTP response.

Begin by importing the csv module from Pythonโ€™s standard library and the HttpResponse class from Django:

utility.py
from django.http import HttpResponse
import csv

This setup will allow us to process the data and serve it as a downloadable file.

Next, we will implement the export_csv function.

utility.py
def export_csv(data) :
    collumns = data.model._meta.fields #? gets the metadata of the model`s parameters (fields)
    collumns_name = [collumn.name for collumn in collumns]
    
    response = HttpResponse(content_type="text/csv") #? will return a csv file
    response["Content-Disposition"] = f"attachment; '{data.model}.csv'"

    csv_creator = csv.writer(response, delimiter=";") #? the rows will come with ';' 

    #? first row will be the collumns
    csv_creator.writerow(collumns_name)

    #?writing the lines themselves
    for line in data.values_list():
        csv_creator.writerow(line)  #? writes each row of data as a list of values to the csv file.

    return response

The code above:

  • Retrieves model metadata fields from data.model._meta.fields.

  • Extracts field names into collumns_name list for CSV headers.

  • Creates an HTTP response with content_type="text/csv".

  • Sets the response header for file download with a dynamic filename based on the model name.

  • Initializes a CSV writer with semicolon (;) as the delimiter.

  • Writes the column names as the first row in the CSV.

  • Iterates over the rows in data.values_list() and writes each as a row in the CSV.

  • Returns the HTTP response with the CSV file for download.

In the views.py file, import the export_csv function at the top:

views.py
from .utility import filter_product, min_max_price, order_products, secure_password, send_purchase_email, export_csv

Next, we will update the export_report view to incorporate the export functionality using the previously created export_csv function.

views.py
@login_required
def export_report(request, report):
    if request.user.groups.filter(name="Team").exists(): #? verify again if the user is part of a management Team
        if report == "orders" :
            data = Order.objects.filter(finished=True) #? queryset that searches the whole database
        elif report == "client" :
            data = Client.objects.all()
        elif report == "address" :
            data = Adres.objects.all()
        return export_csv(data) #? returns a http response
    else :
        return redirect('manage_store')
  • Decorator: @login_required ensures that the user must be logged in to access the view.

  • Group Check: Verifies if the user belongs to the "Team" group using request.user.groups.filter(name="Team").exists().

  • Report Selection: Based on the report parameter:

    • If report == "orders", retrieves all finished orders with Order.objects.filter(finished=True).

    • If report == "client", retrieves all clients with Client.objects.all().

    • If report == "address", retrieves all addresses with Adres.objects.all().

  • CSV Export: Calls export_csv(data) to generate and return a CSV file with the selected data.

  • Redirection: If the user is not in the "Team" group, redirects to the 'manage_store' page.

Now, when accessing the store management page with a manager account from the Team group, you can export each of the three report types (Address, Clients, and Orders) as a CSV file containing all relevant information.

Export any of the 3 reports
Order report
Client report
Address report

In the following sections, we will begin developing the front-end of our website.

Last updated