Django导出博客为hexo博客

点击量:11

Django导出主要使用render_to_string方法来进行;

可以参考的源码如下:

from article.models import Article
from django.template.loader import render_to_string
posts = Article.objects.all()
for post in posts:
    title = post.title
    title = title.replace('[', '')
    title = title.replace(']', '')
    context = {
        'title': title,
        'cre_date': post.cre_date,
        'updated': post.up_date,
        'content': post.content,
        'category': post.category.name,
        'tag': post.tag
    }
    content = render_to_string('article.html', context)
    filename = 'export/' + post.title + '.md'
    with open(filename, 'w') as f:
        f.write(content)

对应的渲染article.html

title: {{ title }}
date: {{ cre_date | date:"Y/m/d H:i:s" }}
updated: {{ updated | date:"Y/m/d H:i:s" }}
tags: [
{% for tag in tags %}
    '{{ tag.name }}',
{% endfor %}
]
categories: [
    '{{ category }}',
]
---
{{ content | safe }}

运行的时候,python manage.py shell,然后导入export 包即可。

发表评论

电子邮件地址不会被公开。 必填项已用*标注