You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
2.0 KiB
62 lines
2.0 KiB
# -*- coding: utf-8 -*-
|
|
import xlrd
|
|
from django.core.management.base import BaseCommand
|
|
from django.conf import settings
|
|
from article.models import Article
|
|
from import_xls.excel_settings import article_sett
|
|
from django.db import IntegrityError
|
|
|
|
|
|
NEWS_FILE = settings.MEDIA_ROOT+'/import/news.xls'
|
|
|
|
|
|
class Command(BaseCommand):
|
|
def handle(self, *args, **options):
|
|
|
|
f = open(NEWS_FILE, 'r')
|
|
book = xlrd.open_workbook(file_contents=f.read())
|
|
sheet = book.sheet_by_index(0)
|
|
row_list = [sheet.row_values(row_number) for row_number in range(sheet.nrows)]
|
|
labels = [label for label in row_list[0]]
|
|
existing = 0
|
|
for row_number, row in enumerate(row_list[2:]):
|
|
|
|
published = row[4]
|
|
if row[0] != '':
|
|
# in first column ids
|
|
try:
|
|
object = Article.objects.language('ru').get(id=int(row[0]))
|
|
object.type = Article.news
|
|
object.save()
|
|
print(object.type)
|
|
continue
|
|
except ValueError:
|
|
|
|
object = Article(type=Article.news)
|
|
object.translate('ru')
|
|
except Article.DoesNotExist:
|
|
object = Article(id= int(row[0]))
|
|
object.translate('ru')
|
|
existing += 1
|
|
else:
|
|
# if id blank - its a new place
|
|
object = Article(type=Article.news)
|
|
object.translate('ru')
|
|
|
|
for col_number, cell in enumerate(row):
|
|
|
|
label = labels[col_number]
|
|
setting = article_sett.get(label)
|
|
if setting is None:
|
|
continue
|
|
|
|
field_name = setting['field']
|
|
func = setting.get('func')
|
|
value = func(cell)
|
|
setattr(object, field_name, value)
|
|
object.publish_date = published
|
|
try:
|
|
object.save()
|
|
except Exception, e:
|
|
print(e)
|
|
|
|
|