Last active
September 12, 2019 20:50
-
-
Save thatbudakguy/5dea1dc527f3f0eb678011f8a413e884 to your computer and use it in GitHub Desktop.
cdhweb blog post migration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cdhweb.settings') | |
import django | |
django.setup() | |
from xml.etree import ElementTree | |
from dateutil.parser import parse | |
from mezzanine.core.models import CONTENT_STATUS_DRAFT | |
from cdhweb.blog.models import BlogPost | |
from cdhweb.people.models import Person | |
tree = ElementTree.parse('old_blogposts.xml') | |
root = tree.getroot() | |
ns = { | |
'wp': 'http://wordpress.org/export/1.2/', | |
'dc': 'http://purl.org/dc/elements/1.1/', | |
'content': 'http://purl.org/rss/1.0/modules/content/', | |
} | |
posts = [i for i in root.iter('item') if i.find('wp:post_type', ns).text == 'post'] | |
published_posts = [p for p in posts if p.find('wp:status', ns).text == 'publish'] | |
try: | |
admin = Person.objects.get(username='admin') | |
except Person.DoesNotExist: | |
admin = Person.objects.create_user('admin', | |
first_name='CDH Staff', | |
is_active=False) | |
def create_post(post: ElementTree): | |
title = post.find('title', ns).text | |
pub_date = parse(post.find('pubDate', ns).text) | |
slug = post.find('wp:post_name', ns).text | |
content = post.find('content:encoded', ns).text | |
try: | |
creator = Person.objects.get(username=post.find('dc:creator', ns).text) | |
except Person.DoesNotExist: | |
creator = admin | |
new_post = BlogPost.objects.create( | |
title=title, | |
publish_date=pub_date, | |
content=content, | |
status=CONTENT_STATUS_DRAFT, | |
) | |
new_post.users.add(creator) | |
new_post.save() | |
for post in published_posts: | |
create_post(post) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment