django搭建个人博客06,发布文章页

来源:互联网 发布:傲剑易经升级数据大全 编辑:程序博客网 时间:2024/05/02 01:47

安装markdown模块

  进入虚拟环境
  1.python3 -m pip install markdown


使用class FormView创建文章

  1.从modle创建自定义的ModelForm
ModelForm
  vim www/forms.py

import datetimeimport markdownfrom django.forms import ModelForm,Textareafrom .models import tb_articlesfrom django.utils.translation import ugettext_lazy as _class ArticlePublishForm(ModelForm):    class Meta:        model=tb_articles        exclude=["articleID","content_html","created","updated"]        labels={            'title':_('文章标题'),            'content_md':_('文章内容'),            'tagID':_('文章分类'),        }        widgets={            'abstract':Textarea(attrs={'cols':30,'rows':5}),        }    def save(self,username):        cd=self.cleaned_data        title=cd['title']        content_md=cd['content_md']        content_html=markdown.markdown(cd['content_md'])        tag=cd['tagID']        abstract=cd['abstract']        created=datetime.datetime.now()        updated=datetime.datetime.now()        article=tb_articles(title=title,content_md=content_md,content_html=content_html,abstract=abstract,        tagID=tag,created=created,updated=updated)        article.save()

  2.从FormView类创建自定义View并使用ArticlePulishForm作为form源
FormView

from .forms import ArticlePublishFormfrom django.views.generic.edit import FormViewclass ArticlePublishView(FormView):    template_name='www/article_publish_base.html'    form_class=ArticlePublishForm    success_url='blogs/0/1'    def form_valid(self,form):        form.save(self.request.user.username)        return super(ArticlePublishView,self).form_valid(form)

  3.编辑article_publish_base.html,并引入markdown编辑器
Markdown Editor

<!-- article_publish_base.html -->{% extends "www/www_base.html" %}{% load static %}{% block selfstyle %}<title>add new</title><link rel="stylesheet" href="http://lab.lepture.com/editor/editor.css" /><script src="http://lab.lepture.com/editor/editor.js"></script><script src="http://lab.lepture.com/editor/marked.js"></script>{% endblock %}{% block content %}<div id="pub_article"><form action="" method="post">{% csrf_token %}{{ form.as_p}}<input type="submit" value="Send message"></form></div>{% endblock %}<!-- end article_publish_base.html -->

配置url查看结果

 url(r'^article/publish/$',views.ArticlePublishView.as_view(),name="articlePublish"),

blogs/article/publish

0 0