Django开发-3

支持Markdown

  • 安装

    >pip install markdown
    
  • 修改detail视图,支持markdown

    ...
    def detail(request,pk):
        post = get_object_or_404(Post, pk=pk)
        #把markdown转换成html标签
        post.body = markdown.markdown(post.body, extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.codehilite',
            'markdown.extensions.toc',
        ])
        context = {'post':post}
        return render(request,'blog/detail.html',context)
    ...
    
  • detail.html增加safe标签,解除html转义

    <div class="entry-content clearfix">
        {{ post.body|safe }}
    </div>
    

自动生成目录

  • 修改views.py
def detail(request,pk):
    post = get_object_or_404(Post, pk=pk)
    md = markdown.Markdown(extensions=[
        'markdown.extensions.extra',
        'markdown.extensions.codehilite',
        'markdown.extensions.toc',
    ])
    # 把markdown转换成html标签
    post.body = md.convert(post.body)
    post.toc = md.toc  #目录
    context = {'post':post}
    return render(request,'blog/detail.html',context)
  • 修改detail.html
{% block aside %}
                <div class="widget widget-content">
                    <h3 class="widget-title">文章目录</h3>
                    {{ post.toc|safe }}
                </div>
...

自动摘要生成

重写save,修改摘要

models.py

class Post(models.Model):
 ...
    def save(self, *args, **kwargs):
        self.modified_time = timezone.now()  #修改时间的自动调整
        #生成摘要
        md = markdown.Markdown(extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.codehilite',
        ])
        self.excerpt = strip_tags(md.convert(self.body))[:50]
        super().save(*args,**kwargs)

前端使用摘要标签

index.html

</header>
                    <div class="entry-content clearfix">
                        <p>{{ post.excerpt }}</p>
  • 方法2:直接用模板过滤器

    index.html

                        <div class="entry-content clearfix">
                            <p>{{ post.body|truncatechars:60 }}</p>
    

自定义模板标签

  • 创建blog/templatetags/blog_extras.py,templatetags是package
  • 创建templates/blog/inclusions目录,用来存放模板标签html

最新文章

  • 定义模板标签

blog_extras.py添加

from blog.models import Post,Category,Tag
from django import template
register = template.Library()

@register.inclusion_tag('blog/inclusions/_recent_posts.html',takes_context=True)
def show_recent_posts(context,num=3):
    post_list = Post.objects.all().order_by('-create_time')[:num]
    return {'recent_post_list':post_list}
  • 添加模板

创建templates/blog/inclusions/_recent_posts.html

<div class="widget widget-recent-posts">
    <h3 class="widget-title">最新文章</h3>
    <ul>
        {% for post in recent_post_list %}
        <li>
            <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
        </li>
        {% empty %}
        暂无文章!
        {% endfor %}
    </ul>
</div>
  • 使用模板标签

    base.html

    {% load blog_extras %}
    ...
              <aside class="col-md-4">
                    {% block aside %}
                    {% endblock aside %}
                    {% show_recent_posts %}
                </aside>
    

分类

  • 注册分类模板标签:show_categories

    blog_extras.py

    ...
    @register.inclusion_tag('blog/inclusions/_categories.html', takes_context=True)
    def show_categories(context):
        return {'category_list':Category.objects.all()}
    
  • 创建模板:_categories.html

     <div class="widget widget-category">
        <h3 class="widget-title">分类</h3>
        <ul>
            {% for cate in category_list %}
            <li>
                <a href="#">{{ cate.name }} <span class="post-count">(13)</span></a>
            </li>
            {% empty %}
            暂无分类!
            {% endfor %}
        </ul>
    </div>
    
  • 使用模板标签

base.html

...
            <aside class="col-md-4">
                ...
                {% show_categories %}
            </aside>

练习1:模板标签

归档

标签云

其他页面

分类

  • 视图函数

    views.py

    from .models import Post,Category
    ...
    def category(request, pk):
        cate = get_object_or_404(Category, pk=pk) #类别对象
        post_list = Post.objects.filter(category=cate).order_by('-create_time')
        return render(request, 'blog/index.html', context={'post_list':post_list})
    
  • url映射

    blog/urls.py

    urlpatterns = [
      ...
        path('categories/<int:pk>', views.category, name='category'),
    ]
    
  • 模板页面跳转

    • 修改blog/inclusions/_categories.html
...
<li>
            <a href="{% url 'blog:category' cate.pk %}">{{ cate.name }} <span class="post-count">(13)</span></a>
...

练习2

标签页

归档页

部署

环境搭建

  • python3安装、虚拟环境,依赖包

  • 激活虚拟环境

    source /home/shuyun/web/bin/activate
    
  • 创建项目目录并授权给shuyun

    mkdir -p /home/shuyun/program
    chown -R shuyun.shuyun /home/shuyun/program
    
  • 项目打包,上传到服务器(put、svn、git)的/home/shuyun/program

  • 解压项目文件

    cd /home/shuyun/program
    unzip blogproj.zip
    
  • 测试

    cd /home/shuyun/program/blogproj
    python manage.py runserver 0.0.0.0:8000
    

浏览器访问 http://服务器IP:8000

使用gunicorn

  • 确保服务器可以访问公网

  • 安装

    pip3 install gunicorn
    
  • 启动服务到后台

    nohup gunicorn blogproj.wsgi -w 2 -k gthread -b 0.0.0.0:8000 &
    

    浏览器访问: http://服务器IP:8000

Nginx

  • 安装

    # yum install nginx -y
    
  • 配置修改

    • /etc/nginx/nginx.conf

      user shuyun;
      ...
      
    • 创建/etc/nginx/conf.d/blogproj.conf

      server {
          charset utf-8;
          listen       8080;
          server_name  0.0.0.0;
      
          location /static {
          alias /home/shuyun/program/blogproj/static;
          }
      
          location / {
          proxy_set_header Host $host;
          proxy_pass http://127.0.0.1:8000;
          }
      }
      
  • 启动服务

    # service nginx start
    
  • 收集静态文件

    $ python manage.py collectstatic
    

浏览器访问:http://192.168.89.200:8080/

练习3

创建comments评论应用,实现评论添加、查看、删除

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本教程内容已过时,更新版教程请访问: Django 博客开发入门教程。 本节是 Django Blog 项目的开篇...
    追梦人物阅读 57,853评论 93 169
  • 久违的晴天,家长会。 家长大会开好到教室时,离放学已经没多少时间了。班主任说已经安排了三个家长分享经验。 放学铃声...
    飘雪儿5阅读 7,609评论 16 22
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    迷月闪星情阅读 10,629评论 0 11
  • 可爱进取,孤独成精。努力飞翔,天堂翱翔。战争美好,孤独进取。胆大飞翔,成就辉煌。努力进取,遥望,和谐家园。可爱游走...
    赵原野阅读 2,804评论 1 1
  • 在妖界我有个名头叫胡百晓,无论是何事,只要找到胡百晓即可有解决的办法。因为是只狐狸大家以讹传讹叫我“倾城百晓”,...
    猫九0110阅读 3,368评论 7 3