I have a text field in models.py
where I can input text content for a blog using the admin.
I want to be able to write the content for this text field in markdown format, but I'm using Django 1.6 and django.contrib.markup
is not supported anymore.
I can't find anywhere that has a tutorial and runs through adding markdown to a text field in Django 1.6. Can someone look at my .py
files and help me implement markdown to my app.
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)
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)
<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>
Thank you for your answers and suggestions, but I've decided to use markdown-deux.
Here's how I did it:
pip install django-markdown-deux
Then I did pip freeze > requirements.txt
to make sure that my requirements file was updated.
Then I added 'markdown_deux' to the list of INSTALLED_APPS:
INSTALLED_APPS = (
...
'markdown_deux',
...
)
Then I changed my template index.html
to:
{% 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>
Ah, I met with the same problem several months ago, and I found the easiest and most robust solution is to use Github Markdown API.
Here is the code I use for my blog, which I believe will help you more or less. btw I use Python 3 so the encoding part may be different from 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()
My code is hosted on github, you can find it here
And My blog is http://laike9m.com.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With