Skip to content

Commit

Permalink
Improved Category import.
Browse files Browse the repository at this point in the history
  • Loading branch information
Corey Oordt committed Aug 22, 2011
1 parent 3e8a10a commit 3fe5004
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
14 changes: 11 additions & 3 deletions categories/management/commands/import_categories.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from django.core.management.base import BaseCommand, CommandError
from categories.models import Category
from django.template.defaultfilters import slugify
from django.db import transaction

class Command(BaseCommand):
"""Import category trees from a file."""
Expand All @@ -22,17 +23,23 @@ def get_indent(self, string):
else:
return ' ' * indent_amt


@transaction.commit_on_success
def make_category(self, string, parent=None, order=1):
"""
Make and save a category object from a string
"""
return Category.objects.create(
cat = Category(
name=string.strip(),
slug=slugify(string.strip())[:49],
parent=parent,
#parent=parent,
order=order
)
cat._tree_manager.insert_node(cat, parent, 'last-child', True)
cat.save()
if parent:
parent.rght = cat.rght + 1
parent.save()
return cat

def parse_lines(self, lines):
"""
Expand Down Expand Up @@ -60,6 +67,7 @@ def parse_lines(self, lines):
else:
# We are back to a zero level, so reset the whole thing
current_parents = {0: self.make_category(line)}
current_parents[0]._tree_manager.rebuild()

def handle(self, *file_paths, **options):
"""
Expand Down
1 change: 1 addition & 0 deletions categories/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from categories.tests.category_import import *
from categories.tests.templatetags import *
from categories.tests.manager import *

__fixtures__ = ['categories.json']
12 changes: 12 additions & 0 deletions categories/tests/category_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,23 @@ def _import_file(self, filename):
def testImportSpaceDelimited(self):
Category.objects.all().delete()
self._import_file('test_category_spaces.txt')

items = Category.objects.all()

self.assertEqual(items[0].name, 'Category 1')
self.assertEqual(items[1].name, 'Category 1-1')
self.assertEqual(items[2].name, 'Category 1-2')


def testImportTabDelimited(self):
Category.objects.all().delete()
self._import_file('test_category_tabs.txt')

items = Category.objects.all()

self.assertEqual(items[0].name, 'Category 1')
self.assertEqual(items[1].name, 'Category 1-1')
self.assertEqual(items[2].name, 'Category 1-2')


def testMixingTabsSpaces(self):
Expand Down

0 comments on commit 3fe5004

Please sign in to comment.