christchurch_django / sermons / management / commands / import_sermons.py

"""
import_sermons command
"""
import os
import os.path

from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand

from sermons.models import Sermon, SERMONS_PATH
from sermons.tags import set_attrs_from_filename

class Command(BaseCommand):

    def handle(self, *args, **options):
        from django.conf import settings
        sermon_dir = os.path.join(settings.MEDIA_ROOT, SERMONS_PATH)
        sermons = []
        errors = []
        for f in os.listdir(sermon_dir):
            if f.endswith('.mp3'):
                s = Sermon(sermon=os.path.join(SERMONS_PATH, f))
                set_attrs_from_filename(s)
                try:
                    s.full_clean()
                    s.published = True
                    sermons.append(s)
                except ValidationError as e:
                    errors.append("%s could not be imported due to missing/bad data for fields: %s" % (f, ','.join(e.message_dict.keys())))

        if len(errors) > 0:
            for e in errors:
                self.stderr.write(e + '\n')
        else:
            for s in sermons:
                if Sermon.objects.filter(date_delivered=s.date_delivered, time_delivered=s.time_delivered).exists():
                    self.stderr.write("Skipping duplicate: %s\n" % s.sermon.url)
                else:
                    self.stdout.write("Importing sermon:   %s\n" % s.sermon.url)
                    s.save()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.