如何在Django中使用MarkDown

1. MarkDown插入的使用要使用form表单操作

2.安装django-mdeditor

3.在settings.py做如下配置

INSTALLED_APPS = [
  ...
  'mdeditor',
]

4.在urls.py里面配置下面路由

urlpatterns = [
...
url(r'mdeditor/', include('mdeditor.urls')),
]

5.以我的文章为例在子程序article中添加forms.py文件

from django import forms
from .models import Article
from mdeditor.fields import MDTextFormField

class CreateArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = ('title', 'content', 'subject')

6.article/models.py中

from django.db import models

from user.models import User
from subject.models import Subject

from mdeditor.fields import MDTextField

# Create your models here.


class Article(models.Model):
    '''
    文章数据模型
    '''
    id = models.AutoField(primary_key=True,verbose_name='文章编号')
    title = models.CharField(max_length=50,verbose_name='文章标题')
    content = MDTextField()  #  form 表单中定义的MD文本类型
    publish_time = models.DateTimeField(auto_now_add=True,verbose_name='发表时间')
    last_update_time = models.DateTimeField(auto_now=True,verbose_name='最后一次修改时间')

    read_count = models.IntegerField(default=0,verbose_name='阅读次数')
    comment_count = models.IntegerField(default=0,verbose_name='评论次数')

    #关联用户
    user = models.ForeignKey(User,on_delete=models.CASCADE,verbose_name='用户')
    subject = models.ForeignKey(Subject, null=True, blank=True, on_delete=models.CASCADE,
                                verbose_name='属于哪一个专题')

7.article/views.py中

def article_pub(request):   
 if request.method == 'POST':
        form = CreateArticleForm(request.POST)
        if form.is_valid():
            form.instance.user = request.session['login_user']
            form.save()
            return redirect('article:article_detail', article_id=form.instance.id)
    else:
        form = CreateArticleForm()

    return render(request, 'article/article_pub.html', {'form': form})

8. article/article_pub.html页面中

html



    
    Title
    



发表文章

{% csrf_token %} {{form.media}} {{form.as_p}}

你可能感兴趣的:(如何在Django中使用MarkDown)