bgneal@646: """ bgneal@646: topic_export.py bgneal@646: bgneal@646: A management command to export a forum topic by rendering it through a given bgneal@646: template. bgneal@646: bgneal@646: """ bgneal@647: from __future__ import with_statement bgneal@646: from optparse import make_option bgneal@646: import re bgneal@646: bgneal@991: from django.conf import settings bgneal@646: from django.core.management.base import LabelCommand, CommandError bgneal@646: from django.template.loader import render_to_string, TemplateDoesNotExist bgneal@646: bgneal@646: from forums.models import Topic bgneal@646: bgneal@646: bgneal@646: SRC_RE = re.compile(r'src="/media/') bgneal@991: SRC_REPL = 'src="{}://surfguitar101.com/media/'.format(settings.SITE_SCHEME) bgneal@646: bgneal@646: bgneal@646: class Command(LabelCommand): bgneal@646: help = "Exports a forum topic thread by rendering it through a given template" bgneal@646: option_list = LabelCommand.option_list + ( bgneal@646: make_option('-t', '--template', bgneal@646: default='forums/topic_export.html', bgneal@646: help='template to render'), bgneal@646: make_option('-o', '--output', bgneal@646: default=None, bgneal@646: help='output filename [default: stdout]'), bgneal@646: ) bgneal@646: bgneal@646: def handle_label(self, tid, **opts): bgneal@646: """Fetch the topic and related posts. Render through a template. bgneal@646: Optionally write content to an output file. bgneal@646: bgneal@646: """ bgneal@646: try: bgneal@646: tid = int(tid) bgneal@646: except ValueError: bgneal@646: raise CommandError('topic ID must be an integer') bgneal@646: bgneal@646: template_name = opts['template'] bgneal@646: output_filename = opts['output'] bgneal@646: bgneal@646: try: bgneal@646: topic = Topic.objects.get(pk=tid) bgneal@646: except Topic.DoesNotExist: bgneal@646: raise CommandError('topic ID does not exist') bgneal@646: bgneal@680: posts = topic.posts.select_related('user') bgneal@646: bgneal@646: try: bgneal@646: content = render_to_string(template_name, {'topic': topic, 'posts': bgneal@646: posts}) bgneal@646: except TemplateDoesNotExist: bgneal@646: raise CommandError('template does not exist') bgneal@646: bgneal@646: # fix up smiley images bgneal@646: content = SRC_RE.sub(SRC_REPL, content) bgneal@646: bgneal@646: content = content.encode('utf-8') bgneal@646: bgneal@646: if output_filename: bgneal@646: with open(output_filename, 'w') as fp: bgneal@646: fp.write(content) bgneal@646: else: bgneal@646: self.stdout.write(content)