1. 程式人生 > >搭建自己的部落格(十九):新增簡單的評論功能

搭建自己的部落格(十九):新增簡單的評論功能

因為評論可以作為一個模組,所以單獨建立一個app,專門用來處理評論。

1、變化的部分

2、上程式碼

{# 引用模板 #}
{% extends 'base.html' %}

{% load staticfiles %}
{% block header_extends %}
    <link rel="stylesheet" href="{% static 'blog/blog.css' %}">
{% endblock %}


{# 標題 #}
{% block title %}
    {{ blog.title }}
{% endblock %}

{# 內容#}
{% block content %}
    
<div class="container"> <div class="row"> <div class="col-6 offset-1"> <ul class="blog-info-description"> <h3>{{ blog.title }}</h3> <li>作者:{{ blog.author }}</li> {# 時間過濾器讓時間按照自己需要的格式過濾 #}
<li>釋出日期:{{ blog.created_time|date:"Y-m-d H:n:s" }}</li> <li>分類: <a href="{% url 'blogs_with_type' blog.blog_type.pk %}"> {{ blog.blog_type }} </a> </
li> <li>閱讀({{ blog.get_read_num }})</li> </ul> <p class="blog-content">{{ blog.content|safe }}</p> <p>上一篇: {% if previous_blog %} <a href="{% url 'blog_detail' previous_blog.pk %}">{{ previous_blog.title }}</a> {% else %} <span>沒有了</span> {% endif %} </p> <p>下一篇: {% if next_blog %} <a href="{% url 'blog_detail' next_blog.pk %}">{{ next_blog.title }}</a> {% else %} <span>沒有了</span> {% endif %} </p> </div> </div> <div class="row"> <div class="col-6 offset-1"> <div style="margin-top: 2em;border: 1px dashed;padding: 2em">提交評論區域 {% if user.is_authenticated %} 已登入 {% else %} 未登入 <form action="{% url 'login' %}" method="post"> {% csrf_token %} <input type="text" name="username"> <input type="password" name="password"> <input type="submit" value="登入"> </form> {% endif %} </div> <div style="margin-top: 2em;border: 1px dashed;padding: 2em">評論列表區域</div> </div> </div> </div> {% endblock %} {% block js %} <script> $(".nav-blog").addClass("active").siblings().removeClass("active"); </script> {% endblock %}
blog_detail.html
from django.shortcuts import render, get_object_or_404
from .models import Blog, BlogType
from django.core.paginator import Paginator
from django.conf import settings
from django.db.models import Count
from read_statistics.utils import read_statistics_once_read


# 分頁部分公共程式碼
def blog_list_common_data(requests, blogs_all_list):
    paginator = Paginator(blogs_all_list, settings.EACH_PAGE_BLOGS_NUMBER)  # 第一個引數是全部內容,第二個是每頁多少
    page_num = requests.GET.get('page', 1)  # 獲取url的頁面引數(get請求)
    page_of_blogs = paginator.get_page(page_num)  # 從分頁器中獲取指定頁碼的內容

    current_page_num = page_of_blogs.number  # 獲取當前頁
    all_pages = paginator.num_pages
    if all_pages < 5:
        page_range = list(
            range(max(current_page_num - 2, 1),
                  min(all_pages + 1, current_page_num + 3)))  # 獲取需要顯示的頁碼 並且剔除不符合條件的頁碼
    else:
        if current_page_num <= 2:
            page_range = range(1, 5 + 1)
        elif current_page_num >= all_pages - 2:
            page_range = range(all_pages - 4, paginator.num_pages + 1)
        else:
            page_range = list(
                range(max(current_page_num - 2, 1),
                      min(all_pages + 1, current_page_num + 3)))  # 獲取需要顯示的頁碼 並且剔除不符合條件的頁碼

    blog_dates = Blog.objects.dates('created_time', 'month', order='DESC')
    blog_dates_dict = {}
    for blog_date in blog_dates:
        blog_count = Blog.objects.filter(created_time__year=blog_date.year, created_time__month=blog_date.month).count()
        blog_dates_dict = {
            blog_date: blog_count
        }

    return {
        'blogs': page_of_blogs.object_list,
        'page_of_blogs': page_of_blogs,
        'blog_types': BlogType.objects.annotate(blog_count=Count('blog')),  # 新增查詢並新增欄位
        'page_range': page_range,
        'blog_dates': blog_dates_dict
    }


# 部落格列表
def blog_list(requests):
    blogs_all_list = Blog.objects.all()  # 獲取全部部落格
    context = blog_list_common_data(requests, blogs_all_list)
    return render(requests, 'blog/blog_list.html', context)


# 根據型別篩選
def blogs_with_type(requests, blog_type_pk):
    blog_type = get_object_or_404(BlogType, pk=blog_type_pk)
    blogs_all_list = Blog.objects.filter(blog_type=blog_type)  # 獲取全部部落格
    context = blog_list_common_data(requests, blogs_all_list)
    context['blog_type'] = blog_type
    return render(requests, 'blog/blog_with_type.html', context)


# 根據日期篩選
def blogs_with_date(requests, year, month):
    blogs_all_list = Blog.objects.filter(created_time__year=year, created_time__month=month)  # 獲取全部部落格
    context = blog_list_common_data(requests, blogs_all_list)
    context['blogs_with_date'] = '{}年{}日'.format(year, month)
    return render(requests, 'blog/blog_with_date.html', context)


# 部落格詳情
def blog_detail(requests, blog_pk):
    blog = get_object_or_404(Blog, pk=blog_pk)
    obj_key = read_statistics_once_read(requests, blog)

    context = {
        'blog': blog,
        'previous_blog': Blog.objects.filter(created_time__gt=blog.created_time).last(),
        'next_blog': Blog.objects.filter(created_time__lt=blog.created_time).first(),
    }
    response = render(requests, 'blog/blog_detail.html', context)
    response.set_cookie(obj_key, 'true')

    return response
blog下的views.py
from django.contrib import admin
from .models import Comment
# Register your models here.


@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    list_display = ('content_object', 'text', 'comment_time', 'user')
comment下的admin.py
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.auth.models import User


# Create your models here.

class Comment(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    text = models.TextField()
    comment_time = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
comment下的models.py
"""
Django settings for myblog project.

Generated by 'django-admin startproject' using Django 2.1.3.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ea+kzo_5k^[email protected]([email protected]*+w5d11=0mp1p5ngr'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ckeditor',
    'ckeditor_uploader',
    'blog.apps.BlogConfig',  # 將自己建立的app新增到設定中
    'read_statistics.apps.ReadStatisticsConfig',  # 註冊閱讀統計app
    'comment.apps.CommentConfig',  # 註冊評論

]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'blog.middleware.mymiddleware.My404',  # 新增自己的中介軟體
]

ROOT_URLCONF = 'myblog.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'myblog.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    # }
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'myblogs',  # 要連線的資料庫,連線前需要建立好
        'USER': 'root',  # 連線資料庫的使用者名稱
        'PASSWORD': 'felixwang',  # 連線資料庫的密碼
        'HOST': '127.0.0.1',  # 連線主機,預設本級
        'PORT': 3306  # 埠 預設3306
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

# LANGUAGE_CODE = 'en-us'
# 語言
LANGUAGE_CODE = 'zh-hans'

# TIME_ZONE = 'UTC'
# 時區
TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

# 不考慮時區
USE_TZ = False

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]

# media
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# 配置ckeditor
CKEDITOR_UPLOAD_PATH = 'upload/'

# 自定義引數
EACH_PAGE_BLOGS_NUMBER = 7

# 設定資料庫快取
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_read_num_cache_table',
    }
}
settings.py
"""myblog URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from . import views

urlpatterns = [
    path('', views.home, name='home'),  # 主頁路徑
    path('admin/', admin.site.urls),
    path('ckeditor', include('ckeditor_uploader.urls')),  # 配置上傳url
    path('blog/', include('blog.urls')),  # 部落格app路徑
    path('login/', views.login, name='login'),  # 登入
]

# 設定ckeditor的上傳
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urls.py
# -*- coding: utf-8 -*-
# @Time    : 18-11-7 下午4:12
# @Author  : Felix Wang

from django.shortcuts import render, redirect
from django.contrib.contenttypes.models import ContentType
from django.contrib import auth
from read_statistics.utils import get_seven_days_read_data, get_x_days_hot_data
from blog.models import Blog


def home(requests):
    blog_content_type = ContentType.objects.get_for_model(Blog)
    dates, read_nums = get_seven_days_read_data(blog_content_type)

    context = {
        'read_nums': read_nums,
        'dates': dates,
        'today_hot_data': get_x_days_hot_data(0),  # 獲取今日熱門
        'yesterday_hot_data': get_x_days_hot_data(1),  # 獲取昨日熱門
        'seven_days_hot_data': get_x_days_hot_data(7),  # 獲取周熱門
        'one_month_hot_data': get_x_days_hot_data(30),  # 獲取月熱門
    }
    return render(requests, 'home.html', context)


def login(requests):
    username = requests.POST.get('username', '')
    password = requests.POST.get('password', '')
    user = auth.authenticate(requests, username=username, password=password)
    if user is not None:
        auth.login(requests, user)
        return redirect('/')
    else:
        return render(requests, 'error.html', {'message': '使用者名稱或密碼錯誤'})
myblog下的views.py
{% extends 'base.html' %}
{% load staticfiles %}


{% block title %}
    我的部落格|錯誤
{% endblock %}

{% block content %}
    {{ message }}
{% endblock %}

{% block js %}
    {# 將首頁這個按鈕設定啟用狀態 #}
    <script>
        $(".nav-home").addClass("active").siblings().removeClass("active");
    </script>
{% endblock %}
error.html