Django Import Export CSV Fix
In this tutorial, you'll learn about Django Import Export CSV Fix. We cover key concepts, practical examples, and best practices.
The Problem
Users need to upload CSV files to bulk-create records and download data as CSV. Without django-import-export, you write custom CSV parsing in every view.
Quick Fix
Wrong — manual CSV handling
import csv
from django.http import HttpResponse
def export_csv(request):
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response)
for product in Product.objects.all():
writer.writerow([product.name, product.price])
return response
Output: Works per view. No import validation, no error reporting, no admin integration.
Correct — Resource + Admin
# resources.py
from import_export import resources
from .models import Product
class ProductResource(resources.ModelResource):
class Meta:
model = Product
fields = ['id', 'name', 'price', 'category', 'is_active']
export_order = ['id', 'name', 'price', 'category', 'is_active']
# admin.py
from import_export.admin import ImportExportModelAdmin
from .models import Product
from .resources import ProductResource
class ProductAdmin(ImportExportModelAdmin):
resource_class = ProductResource
list_display = ['name', 'price', 'category', 'is_active']
admin.site.register(Product, ProductAdmin)
Output: Import/export buttons in Django admin. Import validates data and reports errors.
Custom import validation
from import_export import resources, fields
from import_export.widgets import ForeignKeyWidget
class ProductResource(resources.ModelResource):
category = fields.Field(
column_name='category',
attribute='category',
widget=ForeignKeyWidget(Category, 'name')
)
class Meta:
model = Product
skip_unchanged = True
report_skipped = True
def before_import_row(self, row, **kwargs):
if float(row.get('price', 0)) < 0:
raise ValueError(f"Negative price: {row['price']}")
def after_import_row(self, row, row_result, **kwargs):
if row_result.errors:
send_import_error_notification(row_result.errors)
Export with custom queryset
class ProductResource(resources.ModelResource):
class Meta:
model = Product
def get_queryset(self):
return Product.objects.filter(is_active=True).select_related('category')
API import/export
from import_export import resources
from import_export.formats.base_formats import CSV, XLSX
from django.http import HttpResponse
def export_products(request):
resource = ProductResource()
dataset = resource.export()
response = HttpResponse(dataset.csv, content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="products.csv"'
return response
Import from API
def import_products(request):
if request.method == 'POST':
resource = ProductResource()
dataset = resource.create_dataset(request.FILES['file'])
result = resource.import_data(dataset, dry_run=False)
return Response({
'total': result.total_rows,
'imported': result.totals['new'],
'updated': result.totals['update'],
'errors': result.row_errors(),
})
Prevention
- Use
ImportExportModelAdminfor instant import/export in admin. - Define a
ModelResourceper model — it keeps CSV logic centralized. - Use
dry_run=Trueduring import to preview changes before committing.
Common Mistakes with import export csv
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world DJANGO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro