django Markdown问题

时间:2017-09-22 03:36:28

标签: django markdown

的Django:1.11.5

的Python:3.5.2

Markdown 2.6.9 https://pypi.python.org/pypi/Markdown/

views.py

from django.shortcuts import render
from .models import Post
import markdown
def home(request):
    Post_list = Post.objects.all().order_by('-pub_date')
    Post.content = markdown.markdown(Post.content)
    return render(request, 'home.html',
                  context={'Post_list':Post_list})

# Create your views here.

models.py

from django.db import models
import django.utils.timezone as timezone
class Category(models.Model):

    name = models.CharField(max_length=100)


class Post(models.Model):

    title = models.CharField(max_length=256)

    content = models.TextField(blank = True, null = True)

    pub_date = models.DateTimeField(default=timezone.now)

    update_time = models.DateTimeField(auto_now=True)

    category = models.ForeignKey(Category)


# Create your models here.

错误消息

AttributeError at /
'DeferredAttribute' object has no attribute 'strip'
Request Method: GET
Request URL:    http://www.balinzuoqi.com/
Django Version: 1.11.5
Exception Type: AttributeError
Exception Value:    
'DeferredAttribute' object has no attribute 'strip'
Exception Location: /usr/local/lib/python3.5/dist-packages/markdown/__init__.py in convert, line 355
Python Executable:  /usr/bin/python3
Python Version: 3.5.2
Python Path:    
['/data/mysite',
 '/usr/local/bin',
 '/usr/lib/python35.zip',
 '/usr/lib/python3.5',
 '/usr/lib/python3.5/plat-i386-linux-gnu',
 '/usr/lib/python3.5/lib-dynload',
 '/usr/local/lib/python3.5/dist-packages',
 '/usr/lib/python3/dist-packages']

不知道哪里有问题。

删除Post.content = markdown.markdown(Post.content),显示正常!

英语不是我的母语;请原谅输入错误。

1 个答案:

答案 0 :(得分:0)

您正在阅读content并将content写入Post课程,而不是该课程的实例。您需要遍历列表并更新每个实例:

def home(request):
    Post_list = Post.objects.all().order_by('-pub_date')
    for post in Post_list:
        post.content = markdown.markdown(post.content)
    return render(request, 'home.html',
                  context={'Post_list':Post_list})

这是否是将Markdown转换为HTML以传递给模板的推荐方法是另一回事。自从我使用Django以来已经过了几年,但这不是以前的做法。但是,这是一个不同的问题。

无论如何,您实际上没有将任何Markdown文本传递给Markdown解析器,因为您没有使用该类的实例。通过上面添加的for循环,每个'Post'的Markdown内容现在被传递给Markdown解析器。