Skip to content

Commit

Permalink
Merge pull request #360 from ericbuckley/dynamic_default_field
Browse files Browse the repository at this point in the history
fix for fields with a dyanmic default callable
  • Loading branch information
bmihelac committed Dec 11, 2015
2 parents a5296f9 + 98cb7e2 commit ecede04
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
3 changes: 1 addition & 2 deletions import_export/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,7 @@ def clean(self, data):

if not value and self.default != NOT_PROVIDED:
if callable(self.default):
self.default = self.default()
return self.default
return self.default()

return value

Expand Down
11 changes: 11 additions & 0 deletions tests/core/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from __future__ import unicode_literals
import random
import string

from django.db import models
from django.utils.encoding import python_2_unicode_compatible
Expand Down Expand Up @@ -48,3 +50,12 @@ class Entry(models.Model):
class WithDefault(models.Model):
name = models.CharField('Default', max_length=75, blank=True,
default=lambda: 'foo_bar')


class WithDynamicDefault(models.Model):
def random_name():
chars = string.ascii_lowercase
return ''.join(random.SystemRandom().choice(chars) for _ in range(100))

name = models.CharField('Dyn Default', max_length=100,
default=random_name)
16 changes: 15 additions & 1 deletion tests/core/tests/resources_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from import_export import results
from import_export.instance_loaders import ModelInstanceLoader

from core.models import Book, Author, Category, Entry, Profile, WithDefault
from core.models import Book, Author, Category, Entry, Profile, WithDefault, WithDynamicDefault

try:
from django.utils.encoding import force_text
Expand Down Expand Up @@ -587,6 +587,20 @@ def after_save_instance(self, instance, dry_run):
self.assertFalse(result.has_errors())
self.assertEquals(User.objects.get(pk=user.pk).username, 'bar')

def test_import_data_dynamic_default_callable(self):
class DynamicDefaultResource(resources.ModelResource):
class Meta:
model = WithDynamicDefault
fields = ('id', 'name',)

resource = DynamicDefaultResource()
dataset = tablib.Dataset(headers=['id', 'name',])
dataset.append([1, None])
dataset.append([2, None])
resource.import_data(dataset, raise_errors=False)
objs = WithDynamicDefault.objects.all()
self.assertNotEqual(objs[0].name, objs[1].name)


class ModelResourceTransactionTest(TransactionTestCase):

Expand Down

0 comments on commit ecede04

Please sign in to comment.