view news/management/commands/import_old_news.py @ 71:e2868ad47a1e

For Django 1.4, using the new manage.py.
author Brian Neal <bgneal@gmail.com>
date Sat, 14 Apr 2012 16:40:29 -0500
parents madeira/news/management/commands/import_old_news.py@966cde8635c0
children b7cdfdde3999
line wrap: on
line source
"""
import_old_news.py - For importing news stories from the older version of this
website.

"""
import datetime

from django.conf import settings
from django.core.management.base import LabelCommand
from django.utils import simplejson as json
from django.utils.html import linebreaks
import textile

from news.models import News

IMG_TAG = u"""\
<img src="{src}" class="floatLeftBox" alt="{title}" title="{title}" border="0" />"""


class Command(LabelCommand):
    args = '<filename filename ...>'
    help = 'Imports older news stories in JSON format'

    def handle_label(self, filename, **options):
        """
        Process the file of older news stories in JSON. Convert to the new model
        scheme.

        """
        with open(filename, 'rb') as f:
            items = json.load(f)

        for item in items:
            if item['model'] == 'band.news':
                self.process_item(item)

    def process_item(self, item):

        fields = item['fields']

        content = fields['text'].strip()
        if fields['markup_enabled']:
            content = textile.textile(content, encoding='utf-8', output='utf-8')
        else:
            content = linebreaks(fields['text'])

        author = fields['author'].strip()
        if author:
            content += u"<p>\u2013&nbsp;%s" % author

        image = fields['photo'].strip()
        if image:
            caption = fields['photo_caption'].strip()
            caption = caption if caption else 'Image'

            src = u"%s%s" % (settings.MEDIA_URL, image)

            content = IMG_TAG.format(src=src, title=caption) + content

        news = News(id=item['pk'],
                title=fields['title'].strip(),
                date=datetime.datetime.strptime(fields['date'], '%Y-%m-%d'),
                content=content)

        news.save()