Skip to content

Instantly share code, notes, and snippets.

@traverseda
Created November 11, 2014 22:40
Show Gist options
  • Save traverseda/5a131a7d4a2a0273f370 to your computer and use it in GitHub Desktop.
Save traverseda/5a131a7d4a2a0273f370 to your computer and use it in GitHub Desktop.
Add a custom widget to all bigIntegerfields on a django_import_export Model Admin, or otherwise override the modelresource_factory
from import_export.resources import *
from import_export.admin import *
from import_export.widgets import Widget
class NullWidget(Widget):
def render(self, value):
if value == "":
return None
return value
from django.db.models.fields import BigIntegerField
import import_export.fields as ieFields
def modelresource_factory(model, resource_class=ModelResource):
"""
Factory for creating ``ModelResource`` class for given Django model.
"""
attrs = {'model': model}
Meta = type(str('Meta'), (object,), attrs)
class_name = model.__name__ + str('Resource')
class_attrs = {
'Meta': Meta,
}
metaclass = ModelDeclarativeMetaclass
resourceClass=metaclass(class_name, (resource_class,), class_attrs)
for i in model._meta.fields:
if type(i) == BigIntegerField:
resourceClass.fields[i.name].widget = NullWidget()
return resourceClass
class ImportExportModelAdmin(ImportExportModelAdmin):
def __init__(self, *args, **kwargs):
self.ExportMixin=ExportMixin
super(ImportExportModelAdmin, self).__init__(*args, **kwargs)
def get_resource_class(self):
if not self.resource_class:
return modelresource_factory(self.model)
else:
return self.resource_class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment