Answer the question
In order to leave comments, you need to log in
Encoding error, how to fix?
When exporting to cvs I get the following result,
where is the error?
admin.py file code
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
import csv
import datetime
from django.contrib import admin
from .models import Order, OrderItem
def ExportToCSV(modeladmin, request, queryset):
opts = modeladmin.model._meta
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; \
filename=Orders-{}.csv'.format(datetime.datetime.now().strftime("%d/%m/%Y"))
writer = csv.writer(response)
fields = [field for field in opts.get_fields() if not field.many_to_many and not field.one_to_many]
# Первая строка- оглавления
writer.writerow([field.verbose_name.encode("cp1251") for field in fields])
# Заполняем информацией
for obj in queryset:
data_row = []
for field in fields:
value = getattr(obj, field.name)
if isinstance(value, datetime.datetime):
value = value.strftime('%d/%m/%Y')
data_row.append(value)
writer.writerow(str(data_row))
return response
ExportToCSV.short_description = 'Export CSV'
class OrderItemInline(admin.TabularInline):
model = OrderItem
raw_id_field = ['product']
class OrderAdmin(admin.ModelAdmin):
list_display = ['id', 'first_name', 'last_name', 'email', 'addres',
'postal_code', 'city', 'paid', 'created', 'update']
list_filter = ['paid', 'created', 'update']
inlines = [OrderItemInline]
actions = [ExportToCSV]
admin.site.register(Order, OrderAdmin)
Answer the question
In order to leave comments, you need to log in
the title is written with the encoding:
and lines - without:
Here in it and an error.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question