Django-CMS系列 (2) - 利用aldryn庫實現Django CMS 博客系統


 

前言

 

前一文介紹了如何用Clean Blog來美化自己的博客,本文開始介紹用Aldryn News來創建自己的博客內容。

 

本文環境:

Python 2.7.10

Djangocms 3.5

 

aldryn-newsblog

安裝

查看 https://github.com/aldryn/aldryn-newsblog/blob/master/setup.py ,可以看到它的依賴庫如下。

 

REQUIREMENTS = [
    'Django>=1.8,<1.11',
    'python-dateutil',
    'aldryn-apphooks-config>=0.2.4',
    'aldryn-boilerplates>=0.7.2',
    'aldryn-categories>=1.1.0',
    'aldryn-common>=0.1.3',
    'aldryn-people>=1.1.0',
    'aldryn-translation-tools>=0.2.0',
    'backport_collections==0.1',
    'django-appdata>=0.1.4',
    'django-cms>=3.2',
    'djangocms-text-ckeditor',
    'django-filer>=0.9.9',
    'django-parler>=1.4',
    'django-sortedm2m>=1.2.2,!=1.3.0,!=1.3.1',
    'django-taggit',
    'lxml',
    'pytz',
    'six',
    'python-dateutil',
]

 

執行pip安裝

pip install aldryn-newsblog

 

 

最新版本的aldryn-newblog (aldryn-newsblog-2.0.0)不支持django-1.11.11,安裝時django版本會退回到django-1.10.8

 

安裝djangocms-comments,后面在博客頁面添加評論時會用到

pip install djangocms-comments

 

安裝其他的一些aldryn的庫,能實現博客的增強效果

pip install aldryn_background_image

pip install aldryn_bootstrap3

 

配置

 

在settings里面填加INSTALLED_APPS,放在'cms'之后

 

添加下列APPS

 

INSTALLED_APPS = (

    # you will probably need to add these
    'aldryn_apphooks_config',
    'aldryn_categories',
    'aldryn_common',
    'aldryn_newsblog',
    'aldryn_people',
    'aldryn_translation_tools',
    'parler',
    'sortedm2m',
    'taggit',

)

   

確認下面APPS已安裝

 

INSTALLED_APPS = (

    # you'll almost certainly have these installed already
    'djangocms_text_ckeditor',
    'easy_thumbnails',
    'filer',
)

  

 

下面是為了增強效果添加的APPS

INSTALLED_APPS = (

    'djangocms_comments',
    'aldryn_background_image',
    'aldryn_bootstrap3',
    'bootstrap3',
)

  

   

添加boilerplates支持 (可選)  

 

INSTALLED_APPS = (
    'aldryn_boilerplates',    
)

 

   

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'aldryn_boilerplates.staticfile_finders.AppDirectoriesFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

  

 

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.i18n',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.template.context_processors.media',
                'django.template.context_processors.csrf',
                'django.template.context_processors.tz',
                'sekizai.context_processors.sekizai',
                'django.template.context_processors.static',
                'cms.context_processors.cms_settings',
                'aldryn_boilerplates.context_processors.boilerplate',
            ],
            'loaders': [
                'django.template.loaders.filesystem.Loader',
                'aldryn_boilerplates.template_loaders.AppDirectoriesLoader',
                'django.template.loaders.app_directories.Loader',
            ],
        },
    },
]

 

  

 

Django Filer

aldryn News&Blog處理Easy Thumb會用到Django Filer,所以需要添加THUMBNAIL_PROCESSORS元組到setting里

注: 這些在django CMS安裝時其實已完成。在aldryn里又強調了一次,再次檢查確認一下。

 

THUMBNAIL_PROCESSORS = (
    'easy_thumbnails.processors.colorspace',
    'easy_thumbnails.processors.autocrop',
    'filer.thumbnail_processors.scale_and_crop_with_subject_location',
    'easy_thumbnails.processors.filters',
    'easy_thumbnails.processors.background',
)

   

安裝完成后需執行python manage.py migrate進行數據庫同步

  

查看效果

進入菜單『頁』-『高級設置』,點擊應用下拉菜單,如果能看到NewsBlog,說明安裝成功。

添加文章

 

添加應用

進入blog頁面,進入菜單『頁』-『高級設置』,在『應用』菜單里選擇『Newsblog』保存,那么在工具欄會添加『News & Blog』菜單

添加文章

從『News & Blog』下拉菜單里選擇『add new articles』開始添加文章

具體安裝頁面要求的內容添加就可以了

一些字段做簡單介紹

『已被發布』:發布的文章才能被瀏覽

『Is Feature』:精選博客。

『LEAD』:文章摘要。

 

 

下面是博客詳情效果圖

 

 

 

下面是文章列表效果圖

 

添加分類和標簽

在前面文章創建時,如果打開高級設置可以看到,每篇博客都有對應的『標簽』和『分類』,通過設置這些值能夠方便瀏覽尋找博客文章。

 

 

除了在博客頁面處添加外,在主頁點擊創建按鈕彈出的創建對話框也可以創建分類

 

 

『分類』創建頁面如下:

 

添加People

創建People

在博客創建頁面已經有入口可以創建People,如果不創建,它會默認創建一個名為1的People

 

同樣在工具欄創建入口,也可以直接創建People。

安裝成功后,再次點擊創建,可以看到兩個新的菜單增加了『New person』『New category』,這是aldryn-newsblog添加的兩個插件。

 

 

選中『New person』下一步進入

 

 

添加應用

 

跟Newsblog,People也能直接附着在頁面上,選擇頁面『聯系人』,進入菜單『頁』-『高級設置』,在『應用』菜單里選擇『People』保存即可。

 

下面是我的實現效果圖,這兒主要改了一些css的東西,就不詳述了。

不支持中文

點擊"Download Vcard"下載people vcard時會有如下報錯:

format 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

 

https://www.saltycrane.com/blog/2008/11/python-unicodeencodeerror-ascii-codec-cant-encode-character/

http://www.cnblogs.com/ajianbeyourself/p/4883487.html

 

修改下面兩個文件可支持中文

 

aldryn_people/models.py

 

    def get_vcard(self, request=None):

        return six.b('{}'.format(smart_unicode(vcard)))

   

aldryn_people/vcard.py

 

class Vcard(object):

    def add_line(self, key, value, **params):

        line = '{0}:{1}'.format(key_and_params, smart_str(value))
        self.lines.append(line)

   

博客及樣式

接下來繼續用Clean Blog的樣式進行美化

 

博客內容

 

參考clean blog內容,並將aldryn newsblog的信息嵌入進去。

 

templates\aldryn_newsblog\includes\article.html

 

 

    <div class="post-preview">
        <a href="{% namespace_url 'article-detail' article.slug namespace=namespace default='' %}">
            <h2 class="post-title">
                {% render_model article "title" %}
            </h2>
            {% if article.lead_in %}
            <h3 class="post-subtitle">
                {% if not detail_view %}
                    {% render_model article "lead_in" "" "" "truncatewords:'20'" %}
                {% else %}
                    {% render_model article "lead_in" %}
                {% endif %}
            </h3>
            {% endif %}
        </a>
        <p class="post-meta">Posted by {% include "aldryn_newsblog/includes/author.html" with author=article.author %} on {{ article.publishing_date|date }}    </p>
</div>

  

注意:這兒用truncatechars代替了truncatewords以支持中文。

 

aldryn_newsblog\includes\author.html

{% if author %}
    {% if author.visual %}
        {% thumbnail author.visual "50x50" crop upscale subject_location=author.visual.subject_location as author_image %}
        <img src="{{ author_image.url }}" width="50" height="50" alt="{{ author.name }}">
    {% endif %}
	<a href="{% namespace_url "article-list-by-author" author.slug namespace=namespace default='' %}">
        {{ author.name }}
    </a>

    {% comment %}
    <p>
        <a href="{% namespace_url "article-list-by-author" author.slug namespace=namespace default='' %}">
            {% if author.visual %}
                {% thumbnail author.visual "50x50" crop upscale subject_location=author.visual.subject_location as author_image %}
                <img src="{{ author_image.url }}" width="50" height="50" alt="{{ author.name }}">
            {% endif %}
            {{ author.name }}
        </a>
    </p>
    {% if author.function %}<p>{{ author.function }}</p>{% endif %}
    {% if author.article_count %}<p>{{ author.article_count }}</p>{% endif %}
    {% endcomment %}
{% endif %}

   

aldryn_newsblog\includes\pagination.html

給ul添加pagination類

{% if is_paginated %}
    <ul class="pagination">

   

aldryn_newsblog\article_detail.html

 

給ul添加class "paginitaion",給li添加class "page-item"以及給a添加class "page-link"

 

    <ul class="pagination">
        {% if prev_article %}
            <li class="page-item"><a class="page-link" href="{{ prev_article.get_absolute_url }}">{% trans "Previous Article" %}</a></li>
        {% endif %}
        <li class="page-item"><a class="page-link" href="{% namespace_url "article-list" %}">{% trans "Back to Overview" %}</a></li>
        {% if next_article %}
            <li class="page-item"><a class="page-link" href="{{ next_article.get_absolute_url }}">{% trans "Next Article" %}</a></li>
        {% endif %}
    </ul>

  

 

效果如下:

文章列表:

 

文章內容:

 

 

插件欄

 

在博客頁面,我們想添加一個側欄提供一些額外的功能,比如標簽,搜索等

 

首先修改templates\aldryn_newsblog\base.html文件,添加sidebar plugin,增加css,將頁面設為2欄,左邊為content,右邊為sidebar。

 

{% extends CMS_TEMPLATE %}
{% load cms_tags %}

{% block content %}

<div class="row plugin-bar">
  <div class="content col-lg-8 col-md-8 mx-auto">
    {% block newsblog_content %}
        {# article_list.html and article_detail.html extend this template #}
    {% endblock %}
  </div>

  <div class="sidebar col-lg-4 col-md-4">
    {% placeholder "sidebar" %} 
  </div>	
</div>
{% endblock content %}

   

添加搜索功能

 

修改aldryn_newsblog\plugins\article_search.html, {% comment%}內部為原內容,新增form改用group樣式。

標題也從html中刪除了,后面直接通過插件在頁面添加。

 

 

{% load i18n %}

{% comment %}
<form action="{{ query_url }}" method="get">   
    <label for="search-plugin-{{ instance.pk }}">{% trans "Keyword search" %}</label>    
    <input type="text" name="q" id="search-plugin-{{ instance.pk }}" placeholder="{% trans 'Keyword' %}">

    <input type="hidden" name="max_articles" value="{{ instance.max_articles }}">
    <button type="submit" class="btn btn-primary">{% trans "Go" %}</button>
</form>
{% endcomment %}

<form action="{{ query_url }}" method="get">   
    <div class="row">
      <div class="col-sm-12">
        <div class="input-group">
          <input type="text" name="q" id="search-plugin-{{ instance.pk }}" class="form-control" placeholder="Search for article ..." required>
          <span class="input-group-btn">
            <button class="btn btn-default" type="submit">Go!</button>
          </span>
        </div><!-- /input-group -->
      </div><!-- /.col-sm-12 -->
    </div><!-- /.row -->
</form>

   

在aldryn_newsblog\includes\search_results.html修改結果顯示,基本參考博客列表的樣子做了修改。

 

    <h2>{% trans "Most recent articles containing" %} "{% blocktrans with query=query %} <strong>{{ query }}</strong>"{% endblocktrans %}</h2>
    {% for article in object_list %}
    <div class="post-preview">
        <a href="{% namespace_url "article-detail" article.slug namespace=view.app_config.namespace default='' %}">
            <h3 class="post-title">
                <strong>
                    {% for category in article.categories.all %}
                        {{ category.name }}{% if not forloop.last %}, {% endif %}
                    {% endfor %}
                </strong>
                {% render_model article "title" %}
            </h3>
            {% if article.lead_in %}
            <h4 class="post-subtitle">
                {{ article.lead_in|striptags|truncatewords:"10"|safe }}
            </h4>
            {% endif %}
        </a>
        <p class="post-meta">Posted by {% include "aldryn_newsblog/includes/author.html" with author=article.author %} on {{ article.publishing_date|date }}    </p>
    </div>
    {% endfor %}
    <hr>

   

效果圖如下

下面是搜索結果

 

 

添加標簽功能

 

在templates\aldryn_newsblog\plugins\tags.html,實現非常簡單,因為我打算把一些css相關內容直接在plugin操作。

 

{% load i18n apphooks_config_tags %}

<ul>
    {% comment %}
    <li{% if not newsblog_tag %} class="active"{% endif %}>
        <a href="{% namespace_url "article-list" namespace=instance.app_config.namespace default='' %}">{% trans "All" %}</a>
    </li>
    {% endcomment %}

    {% for tag in tags %}
        {% comment %}
        <li{% if newsblog_tag.id == tag.id %} class="active"{% endif %}>
            <a href="{% namespace_url "article-list-by-tag" tag.slug namespace=instance.app_config.namespace default='' %}">
                {{ tag.name }}
                <span>{{ tag.article_count }}</span>
            </a>
        </li>
        {% endcomment %}
        <a href="{% namespace_url "article-list-by-tag" tag.slug namespace=instance.app_config.namespace default='' %}"><span class="label label-primary" style="background-color: grey;color:white;padding:4px; margin-right: 2px;border-radius: 3px;">{{ tag.name }}</span></a>
    {% endfor %}
</ul>

   

最終我要在插件實現下面的css結構

<div class="text-left text-uppercase text-secondary mb-0" style="margin-top: 50px; margin-left: 20px;">
 <h2>Tags</h2>
  <div class="text-left">
   Plugin
  </div>
</div>

   

首先添加樣式plugin實現 <div class="text-left text-uppercase text-secondary mb-0" style="margin-top: 50px; margin-left: 20px;">

實現<h2>Tags</h2>比較簡單,直接添加文本,設為H2

然后嵌套方式在里面加入標簽插件

 

最終效果圖如下

添加分類功能

 

基本方法同標簽

修改aldryn_newsblog\plugins\categories.html文件,保留內容顯示的部分,其他的留在plugin操作。

 

<ul>
    {% comment %}
    <li{% if not newsblog_category %} class="active"{% endif %}>
        <a href="{% namespace_url "article-list" namespace=instance.app_config.namespace default='' %}">{% trans "All" %}</a>
    </li>
    {% endcomment %}
    {% for category in categories %}
        {% comment %}
        <li{% if newsblog_category.id == category.id %} class="active"{% endif %}>
            <a href="{% namespace_url "article-list-by-category" category.slug namespace=instance.app_config.namespace default='' %}">{{ category.name }}</a>
            <span>{{ category.article_count }}</span>
        </li>
        {% endcomment %}
        <a href="{% namespace_url "article-list-by-category" category.slug namespace=instance.app_config.namespace default='' %}" style="background-color: grey;color:white;padding:4px; margin-right: 2px;border-radius: 3px;">{{ category.name }}</a>
    {% endfor %}
</ul>

  

 

其他插件

Cms還提供了其他的插件,比如『精選文章』,『最近文章』,『相關文章』等

最近文章

templates\aldryn_newsblog\plugins\latest_articles.html

參考index.html,添加post-preview class及添加Pager

 

{% load i18n %}
{% load i18n apphooks_config_tags %}

{% for article in article_list %}
<div class="post-preview">
    {% include "aldryn_newsblog/includes/article.html" with namespace=instance.app_config.namespace %}
</div>
{% empty %}
    <p>{% trans "No items available" %}</p>
{% endfor %}

<!-- Pager -->
<div class="clearfix">
<a class="btn btn-primary float-right" href="{% namespace_url "article-list" namespace=instance.app_config.namespace default='' %}">Older Posts →</a>
</div>

 

添加評論

安裝app djagnocms-comments

pip install djagnocms-comments

 

在INSTALLED_APPS里添加 'djangocms_comments', 並執行migrate

 

在urls里引入djangocms-comments

urlpatterns += i18n_patterns(
    url(r'^djangocms_comments/', include('djangocms_comments.urls')),
)

  

當前的djangocms-comments版本為djangocms-comments==0.2.2,比較老,有些內容需要適配最新的django版本

djangocms-comments\urls.py,修改urlpatters從元組改為數組

urlpatterns = [
    # url(r'^$', 'main_view', name='app_main'),
    url(r'^ajax/save_comment$', SaveComment.as_view(), name='djangocms_comments_save_comment'),
]

   

原始的djangocms-comments css效果比較差,可以根據自己的需求進行調整,這兒就不進行具體講解了。

 

另外有個插件djangocms_inline_comment,試下來效果不好,沒有繼續研究

 

效果圖如下:

 

 

關注下方公眾號獲取更多文章

參考文檔

https://github.com/aldryn/aldryn-newsblog

http://aldryn-newsblog.readthedocs.io/en/latest/introduction.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM