Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # ============================== file 'xlsx_group_parser.py' ==============================
- from openpyxl import load_workbook
- from posts.models import Group
- def XLSXGroupParser(file):
- wb = load_workbook(file)
- ws = wb.active
- rows = ws.values
- headlines = next(rows)
- index_of_headline = {'title': headlines.index('title'),
- 'slug': headlines.index('slug'),
- 'description': headlines.index('slug')}
- groups = []
- for row in rows:
- group = Group(title=row[index_of_headline['title']],
- slug=row[index_of_headline['slug']],
- description=row[index_of_headline['description']])
- if (not group.title or group.title.isspace() or
- not group.slug or group.slug.isspace()):
- continue
- groups.append(group)
- return groups
- # ============================== file 'xlsx_group_import.py' ==============================
- from django.core.management.base import BaseCommand
- from posts.parsers.xlsx_group_parser import XLSXGroupParser
- class Command(BaseCommand):
- help = 'Import groups from xlsx file'
- def add_arguments(self, parser):
- parser.add_argument('file', type=str)
- def handle(self, *args, **options):
- file_path = options['file']
- groups = XLSXGroupParser(file_path)
- for group in groups:
- group.save()
- self.stdout.write(f'Группа {group.title} сохранена')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement