Не получает экспортировать найденные данные в csv
Не получается экспортировать данные в csv.
При нажатии Download CSV сохраняет весь html,
а требуется только найденные.
Что я не внес еще в views.py?
index.html:
{% if response %}
<h5><a href="{{ response.url }}" download="journal.csv">Download CSV</a></h5>
{% endif %}
viwes.py:
import csv
from django.http import HttpResponse
from django.shortcuts import render
from .models import Journal
from django.db.models import Q, Count, Sum
# Create your views here.
def is_valid_queryparam(param):
return param != '' and param is not None
def BootstrapFilterView(request):
""" Поиск """
qs = Journal.objects.all()
categories = Journal.objects.values('author').distinct().exclude(author__isnull=True)
title_or_author_query = request.GET.get('title_unit')
if title_or_author_query is None:
title_or_author_query = "empty unit" # Если вернется None ["empty", "unit"]
lst_vm_query = title_or_author_query.split()
if request.method == "GET":
# фильтруем значения
qs = qs.filter(Q(title__in=lst_vm_query) # Поиск списоком вм
| Q(author__iexact=title_or_author_query.strip()) # Поиск ВМ без учета регистра
| Q(title__iexact=title_or_author_query) # Поиск ИИС без учета регистра
)
hpc_hdd_jt = qs.values_list('HPC_HDD_JT_CAPACITY', flat=True)
# HINT: No function matches the given name and argument types. You might need to add explicit type casts.
# Так как постргресс не принимает тип данных, убираем /n, и преобразуем строки в int()
# суммируем
# capacity = sum(map(int, " ".join(filter(None, hpc_hdd_jt)).replace("\n", "").split()))
capacity = sum(int(float(p)) for p in " ".join(x for x in hpc_hdd_jt if x is not None).replace("\n", "").split())
# capacity = sum(([int(float(p)) for p in " ".join([x for x in hpc_hdd_jt if x is not None]).replace("/n", "").split()]))
# суммируем проц, память
core = qs.aggregate(Sum('HPC_SERVER_CORE_K'))
ram = qs.aggregate(Sum('HPC_SERVER_RAM'))
# generate csv file
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="journal.csv"'
writer = csv.writer(response)
writer.writerow(['name', 'HPC_HDD_JT_CAPACITY', 'HPC_SERVER_CORE_K', 'HPC_SERVER_RAM'])
for obj in qs: # Add this loop to iterate over the queryset rows and write the data to CSV
writer.writerow([obj.title, obj.HPC_HDD_JT_CAPACITY, obj.HPC_SERVER_CORE_K, obj.HPC_SERVER_RAM])
context = {
'queryset': qs,
'core': core,
'ram': ram,
'capacity': capacity,
'categories': categories,
'response': response
}
return render(request, "index.html", context)
