Django Admin Export Package
A comprehensive Django app that enhances the Django admin interface by providing advanced export functionality for CSV, Excel, and JSON formats. Built with modern Python practices, comprehensive error handling, and extensive customization options.
✨ Features
- Multiple Export Formats: Support for CSV, Excel (XLSX), and JSON exports
- Easy Integration: Simple mixin-based approach for ModelAdmin classes
- Field Customization: Select specific fields, exclude unwanted ones, and customize labels
- Advanced Formatting: Automatic column sizing, header styling, and data type handling
- Error Handling: Comprehensive error handling with user-friendly messages
- Progress Tracking: Built-in progress indicators for large exports
- Internationalization: Full i18n support with Django's translation system
- Backward Compatibility: Legacy function support for existing implementations
- Logging & Monitoring: Built-in logging and audit trails
- Configuration Options: Extensive customization through Django settings
🚀 Quick Start
Installation
pip install django-admin-export
Basic Usage
Add the app to your INSTALLED_APPS:
INSTALLED_APPS = [
# ... other apps
'admin_export',
]
Use the ExportMixin in your ModelAdmin:
from django.contrib import admin
from admin_export.admin import ExportMixin
from .models import Product
@admin.register(Product)
class ProductAdmin(ExportMixin, admin.ModelAdmin):
list_display = ('name', 'price', 'quantity', 'created_at')
# Export configuration
export_fields = ['name', 'price', 'quantity', 'created_at']
export_exclude_fields = ['id', 'updated_at']
export_field_labels = {
'name': 'Product Name',
'price': 'Price (USD)',
'quantity': 'Stock Quantity'
}
export_filename = 'products_export'
📚 Advanced Usage
Custom Field Selection
@admin.register(Product)
class ProductAdmin(ExportMixin, admin.ModelAdmin):
# Export only specific fields
export_fields = ['name', 'price', 'category__name', 'supplier__company_name']
# Exclude sensitive fields
export_exclude_fields = ['password', 'api_key', 'internal_notes']
# Custom field labels
export_field_labels = {
'name': 'Product Name',
'category__name': 'Category',
'supplier__company_name': 'Supplier Company'
}
Format-Specific Configuration
@admin.register(Product)
class ProductAdmin(ExportMixin, admin.ModelAdmin):
# Enable only specific formats
enable_csv_export = True
enable_excel_export = True
enable_json_export = False
# Custom Excel sheet name
export_filename = 'product_catalog'
# Limit export size
export_max_rows = 5000
Advanced Excel Styling
The package automatically applies professional styling to Excel exports:
- Bold headers with gray background
- Auto-adjusted column widths
- Proper data type handling
- Clean, readable formatting
⚙️ Configuration
Django Settings
Add these to your Django settings for global configuration:
# Export configuration
EXPORT_CSV_DELIMITER = ',' # CSV delimiter
EXPORT_EXCEL_SHEET_NAME = 'Data Export' # Default Excel sheet name
EXPORT_MAX_ROWS = 10000 # Maximum rows per export
EXPORT_ENABLE_PROGRESS = True # Enable progress tracking
EXPORT_DEFAULT_FILENAME = 'export' # Default filename prefix
EXPORT_INCLUDE_META_FIELDS = False # Include Django meta fields
EXPORT_ENABLE_LOGGING = True # Enable export logging
EXPORT_LOG_LEVEL = 'INFO' # Log level for exports
Model-Specific Configuration
@admin.register(Product)
class ProductAdmin(ExportMixin, admin.ModelAdmin):
# Basic export settings
export_fields = ['name', 'price', 'category', 'created_at']
export_exclude_fields = ['id', 'updated_at', 'deleted_at']
# Custom labels and formatting
export_field_labels = {
'name': 'Product Name',
'price': 'Price (USD)',
'category': 'Product Category',
'created_at': 'Date Added'
}
# File naming
export_filename = 'product_catalog'
# Export limits
export_max_rows = 5000
# Format selection
enable_csv_export = True
enable_excel_export = True
enable_json_export = False
🔧 API Reference
ExportMixin
The main mixin class that provides export functionality.
Attributes
export_fields: List of field names to export (None = all fields)export_exclude_fields: List of field names to excludeexport_field_labels: Dictionary mapping field names to custom labelsexport_filename: Custom filename for exportsexport_max_rows: Maximum rows to exportenable_csv_export: Enable CSV export (default: True)enable_excel_export: Enable Excel export (default: True)enable_json_export: Enable JSON export (default: False)
Methods
get_export_fields(request): Get list of fields to exportget_export_field_labels(request): Get custom field labelsget_export_filename(request, format_type): Generate export filenameget_export_queryset(request, queryset): Get queryset for exportexport_to_csv(request, queryset): Export to CSVexport_to_excel(request, queryset): Export to Excelexport_to_json(request, queryset): Export to JSON
Utility Functions
from admin_export.utils import get_formatter, validate_export_config
# Get formatter for specific format
formatter = get_formatter('csv', delimiter=';', include_headers=True)
# Validate export configuration
config = validate_export_config({
'format': 'xlsx',
'max_rows': 5000,
'sheet_name': 'Custom Sheet'
})
Forms
from admin_export.forms import ExportConfigurationForm, BulkExportForm
# Export configuration form
form = ExportConfigurationForm(
model_fields=Product._meta.fields,
initial={'format': 'csv', 'max_rows': 1000}
)
# Bulk export form
bulk_form = BulkExportForm(available_models=[
('app.Product', 'Products'),
('app.Category', 'Categories')
])
🧪 Testing
Run the test suite:
python manage.py test admin_export
Or use pytest:
pytest tests/
📖 Examples
Basic Product Export
from django.contrib import admin
from admin_export.admin import ExportMixin
from .models import Product
@admin.register(Product)
class ProductAdmin(ExportMixin, admin.ModelAdmin):
list_display = ('name', 'price', 'category', 'stock', 'created_at')
list_filter = ('category', 'created_at', 'is_active')
search_fields = ('name', 'description')
# Export configuration
export_fields = ['name', 'price', 'category', 'stock', 'created_at']
export_exclude_fields = ['id', 'updated_at', 'deleted_at']
export_field_labels = {
'name': 'Product Name',
'price': 'Price (USD)',
'category': 'Category',
'stock': 'Stock Level',
'created_at': 'Date Added'
}
export_filename = 'product_inventory'
User Management Export
from django.contrib.auth.admin import UserAdmin
from admin_export.admin import ExportMixin
class CustomUserAdmin(ExportMixin, UserAdmin):
# Export configuration
export_fields = ['username', 'email', 'first_name', 'last_name', 'date_joined', 'is_active']
export_exclude_fields = ['password', 'last_login', 'groups', 'user_permissions']
export_field_labels = {
'username': 'Username',
'email': 'Email Address',
'first_name': 'First Name',
'last_name': 'Last Name',
'date_joined': 'Registration Date',
'is_active': 'Account Status'
}
export_filename = 'user_management'
# Enable only CSV and Excel
enable_csv_export = True
enable_excel_export = True
enable_json_export = False
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
Advanced Export with Custom Logic
@admin.register(Order)
class OrderAdmin(ExportMixin, admin.ModelAdmin):
list_display = ('order_number', 'customer', 'total_amount', 'status', 'created_at')
def get_export_fields(self, request):
"""Dynamic field selection based on user permissions."""
if request.user.is_superuser:
return ['order_number', 'customer', 'total_amount', 'status', 'created_at', 'notes']
else:
return ['order_number', 'customer', 'total_amount', 'status', 'created_at']
def get_export_queryset(self, request, queryset):
"""Filter queryset based on user permissions."""
if not request.user.is_superuser:
return queryset.filter(status__in=['confirmed', 'shipped'])
return queryset
def export_to_excel(self, request, queryset):
"""Custom Excel export with additional formatting."""
response = super().export_to_excel(request, queryset)
# Add custom logic here if needed
return response
🔒 Security & Permissions
The package respects Django's permission system:
- Users can only export data they have permission to view
- Export actions are automatically filtered based on user permissions
- Sensitive fields can be excluded from exports
- Audit logging tracks all export activities
🌍 Internationalization
Full support for Django's internationalization system:
from django.utils.translation import gettext_lazy as _
@admin.register(Product)
class ProductAdmin(ExportMixin, admin.ModelAdmin):
export_field_labels = {
'name': _('Product Name'),
'price': _('Price'),
'category': _('Category'),
}
🐛 Troubleshooting
Common Issues
- Export fails silently: Check Django logs and ensure proper error handling
- Large exports timeout: Adjust
EXPORT_MAX_ROWSsetting - Field not found errors: Verify field names in
export_fields - Permission denied: Check user permissions for the model
Debug Mode
Enable debug logging:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'admin_export': {
'handlers': ['console'],
'level': 'DEBUG',
},
},
}
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Setup
git clone https://github.com/NyuydineBill/data2csv.git
cd data2csv
pip install -e ".[dev]"
python manage.py test
Code Style
We use:
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Django community for the excellent framework
- OpenPyXL team for Excel support
- All contributors and users of this package
📞 Support
- Documentation: GitHub README
- Issues: GitHub Issues
- Email: billleynyuy@gmail.com
Made with ❤️ by Nyuydine Bill
Metadata
Release files for django-admin-export-tools 1.0.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| django-admin-export-tools-1.0.3.tar.gz | 24.4 kB | Without provenance | Details for django-admin-export-tools-1.0.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| django_admin_export_tools-1.0.3-py3-none-any.whl | Python 3 | none | any | Details for django_admin_export_tools-1.0.3-py3-none-any.whl |
Total release size: 41.9 kB
Release files / django-admin-export-tools-1.0.3.tar.gz
| Download URL | django-admin-export-tools-1.0.3.tar.gz |
|---|---|
| Size | 24.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
28256fb3fc381121a6d78bf0ee84b3441c060730d8ca89d09ac7c02600587b84
|
|
BLAKE2b-256 checksum How to use checksums |
6d01ce8f5ca4f011027ef62400adbd13017916c1b1e1446695193b3b4e2304f0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.10.12
|
Release files / django_admin_export_tools-1.0.3-py3-none-any.whl
| Download URL | django_admin_export_tools-1.0.3-py3-none-any.whl |
|---|---|
| Size | 17.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
3206bd0c54de31e2db4ac85cf92639f408237df237b09dcd88d5dcd66b2b1397
|
|
BLAKE2b-256 checksum How to use checksums |
0d93681e0b97616520ceac7baeccca6014fbbf3e9999d1d24c6b196546a9aa10
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.10.12
|
Security for django-admin-export-tools 1.0.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.