如何在Django 1.6应用中实现markdown?
我在 models.py
里有一个文本框,可以通过后台输入博客内容。
我想用 markdown 格式来写这个文本框的内容,但我现在用的是 Django 1.6,而 django.contrib.markup
已经不再支持了。
我找不到任何教程来教我如何在 Django 1.6 中给文本框添加 markdown 功能。有没有人能帮我看看我的 .py
文件,教我怎么在我的应用里实现 markdown?
models.py
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateTimeField()
text = models.TextField()
tags = models.CharField(max_length=80, blank=True)
published = models.BooleanField(default=True)
admin.py
from django.contrib import admin
from blogengine.models import Post
class PostAdmin(admin.ModelAdmin):
# fields display on change list
list_display = ['title', 'text']
# fields to filter the change list with
save_on_top = True
# fields to search in change list
search_fields = ['title', 'text']
# enable the date drill down on change list
date_hierarchy = 'pub_date'
admin.site.register(Post, PostAdmin)
index.html
<html>
<head>
<title>My Django Blog</title>
</head>
<body>
{% for post in post %}
<h1>{{ post.title }}</h1>
<h3>{{ post.pub_date }}</h3>
{{ post.text }}
{{ post.tags }}
{% endfor %}
</body>
</html>
3 个回答
1
你可以使用这里实现的旧标记的替代方案 - https://github.com/jamesturk/django-markupfield
7
啊,我几个月前也遇到过同样的问题,我发现最简单且最可靠的解决办法就是使用 Github Markdown API。
这是我在博客中使用的代码,我相信这对你会有帮助。顺便说一下,我用的是Python 3,所以编码部分可能和Python 2有所不同。
# generate rendered html file with same name as md
headers = {'Content-Type': 'text/plain'}
if type(self.body) == bytes: # sometimes body is str sometimes bytes...
data = self.body
elif type(self.body) == str:
data = self.body.encode('utf-8')
else:
print("somthing is wrong")
r = requests.post('https://api.github.com/markdown/raw', headers=headers, data=data)
# avoid recursive invoke
self.html_file.save(self.title+'.html', ContentFile(r.text.encode('utf-8')), save=False)
self.html_file.close()
我的代码托管在github上,你可以在 这里 找到它。
我的博客是 http://laike9m.com。
26
谢谢大家的回答和建议,不过我决定使用 markdown-deux 这个工具。
我这样做的:
pip install django-markdown-deux
接着我运行了 pip freeze > requirements.txt
,这样可以确保我的需求文件是最新的。
然后我把 'markdown_deux' 加入到 INSTALLED_APPS 的列表里:
INSTALLED_APPS = (
...
'markdown_deux',
...
)
接下来,我把我的模板 index.html
修改成:
{% load markdown_deux_tags %}
<html>
<head>
<title>My Django Blog</title>
</head>
<body>
{% for post in post %}
<h1>{{ post.title }}</h1>
<h3>{{ post.pub_date }}</h3>
{{ post.text|markdown }}
{{ post.tags }}
{% endfor %}
</body>
</html>