摘要:上一篇博客系統(tǒng)的博客還沒有實(shí)現(xiàn)評(píng)論,按標(biāo)簽搜索按日期搜索按分類搜索的功能,這篇博客主要是對(duì)以上功能的增加。博客首頁修改主頁的文件有關(guān)分頁顯示的部分上一頁上一頁第頁共頁下一頁下一頁
上一篇‘博客系統(tǒng)’的博客還沒有實(shí)現(xiàn)評(píng)論,按標(biāo)簽搜索、按日期搜索、按分類搜索的功能,這篇博客主要是對(duì)以上功能的增加。
增添評(píng)論第一步:新建app:comment,在主setting.py中添加新app,修改主urls.py文件
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r"^admin/", admin.site.urls), url(r"",include("blog.urls")), url(r"",include("comments.urls")), ]
第二步:編寫評(píng)論的數(shù)據(jù)庫表單
from django.contrib.auth.models import User from django.db import models # Create your models here. from blog.models import Post class Comment(models.Model): user =models.ForeignKey(User,verbose_name="用戶") email = models.EmailField(verbose_name="電子郵箱") text = models.TextField(max_length=255,verbose_name="評(píng)論正文") # auto_now_add=True 自動(dòng)create_time為最新一次更改評(píng)論信息的時(shí)間 create_time = models.DateTimeField(auto_now_add=True,verbose_name="創(chuàng)建時(shí)間") post = models.ForeignKey(Post) class Meta: verbose_name = "評(píng)論" verbose_name_plural = "評(píng)論" def __str__(self): return self.text[:4]
第三步:編寫評(píng)論的路由comment.urls.py和comment.views.py
# comment.views.py from django.shortcuts import render, get_object_or_404,redirect # Create your views here. from blog.models import Post from comments.forms import CommentForm def post_comment(request, id): # 1. 獲取用戶選擇的博客 post = get_object_or_404(Post, id=id) # 2. 如果用戶提交評(píng)論 if request.method == "POST": print(request.POST) form = CommentForm(request.POST) # 2.1 判斷表單是否合法 if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() # 2.2 如果不合法,則提交錯(cuò)誤信息 else: return render(request, "blog/detail.html", context={ "errors": form.errors }) # 3. 如果不是POST請(qǐng)求,訪問用戶詳情頁 return redirect(post.get_url())
# comment.urls from django.conf.urls import url, include from django.contrib import admin from comments import views app_name = "comment" urlpatterns = [ url(r"^comment/blog/(?Pd+)/$",views.post_comment,name="post_comment"), ]
第四步:編寫評(píng)論表單
# 同步與數(shù)據(jù)庫評(píng)論的形式 from comments.models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ["user","email","text"]
第五步:修改HTML文件中關(guān)于評(píng)論的部分
實(shí)現(xiàn)按標(biāo)簽搜索、按日期搜索、按分類搜索的功能
第一步:自定義標(biāo)簽
準(zhǔn)備(必需)工作:
在某個(gè)app下創(chuàng)建一個(gè)名為templatetags(必需,且包名不可變)的包。假設(shè)我們?cè)诿麨閎log的app下創(chuàng)建了一個(gè)templatetags的包,并在該包下創(chuàng)建了一個(gè)名為blog_tags的文件. 確保settings文件中的INSTALLD_APPS內(nèi)必須含有該app 修改setting.py有關(guān)時(shí)間顯示的部分
# TIME_ZONE = "UTC" TIME_ZONE = "Asia/Shanghai" USE_I18N = True USE_L10N = True #如果setting中配置USE_TZ=True則輸出的是UTC時(shí)間(naive time), # 如果setting中配置USE_TZ=False,則該輸出時(shí)間與datetime.datetime.now()完全相同 # USE_TZ = True USE_TZ = False
2. 接下來在blog_tags文件中寫入如下幾行
from django import template register = template.Library()
3. 在模板中使用{% load %} 標(biāo)簽裝載自定義標(biāo)簽或者裝飾器
from django import template from django.db.models import Count from blog.models import Post, Category, Tag register = template.Library() @register.simple_tag def get_recent_posts(num=3): return Post.objects.all().order_by("-create_time")[:num] @register.simple_tag def archives(): return Post.objects.dates(field_name="create_time", kind="month", order="DESC") @register.simple_tag def get_category(): return Category.objects.annotate(num_posts=Count("post")).filter(num_posts__gt=0) @register.simple_tag def get_tags(): # return Tag.objects.all() return Tag.objects.annotate(num_posts = Count("post"))
第二步: 編寫標(biāo)簽查找的路由和視圖函數(shù)
路由
#blog.urls.py from django.conf.urls import url from django.contrib import admin from blog import views app_name = "blog" urlpatterns = [ url(r"^$", views.index, name="index"), url(r"blog/(?Pd+)/$", views.detail, name="detail"), url(r"^archive/(?P d{4})/(?P d{1,2})/", views.archive, name="archive"), url(r"^category/(?P d+)/", views.category, name="category"), url(r"^tag/(?P d+)/", views.tag, name="tag"), url(r"^search", views.search, name="search") ]
視圖函數(shù)
from django.db.models import Q from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 # Create your views here. from markdown import markdown from blog.models import Post, Tag from comments.forms import CommentForm def index(request): # return HttpResponse("ok index!") posts = Post.objects.all() return render(request,"blog/index.html",context={ "posts":posts }) def detail(request,id): # return HttpResponse("ok,%s detail" %(id)) post = Post.objects.get(id=id) post.add_views() form = CommentForm() comments = post.comment_set.all() post.body = markdown(post.body, extensions=["markdown.extensions.extra", "markdown.extensions.codehilite", "markdown.extensions.toc", ], output_format="html") return render(request,"blog/detail.html",context={ "post":post, "comments":comments, "form":form, }) def archive(request,year,month): posts = Post.objects.filter( create_time__year=year, create_time__month=month ).order_by("-create_time") return render(request,"blog/index.html",context={ "posts":posts }) def category(request,id): posts = Post.objects.filter(category_id=id) return render(request,"blog/index.html", context={ "posts":posts }) def tag(request,id): tag = get_object_or_404(Tag,id=id) posts = Post.objects.filter(tags=tag).order_by("-create_time") return render( request, "blog/index.html", context={ "posts": posts } ) def search(request): query = request.GET.get("query",None) posts = Post.objects.filter( Q(title__icontains=query) | Q(body__icontains=query) ) if not posts: return render(request,"blog/index.html", context={ "posts":posts, "message":"沒有找到相關(guān)信息" } ) else: return render(request, "blog/index.html", context={ "posts": posts } )
第三步:修改Html文件,僅截取部分代碼
這里在博客詳情頁需要顯示的是博客的結(jié)構(gòu)(目錄),添加顯示目錄的代碼
修改視圖函數(shù)
def detail(request,id): # return HttpResponse("ok,%s detail" %(id)) post = Post.objects.get(id=id) post.add_views() form = CommentForm() comments = post.comment_set.all() # post.body = markdown(post.body, # extensions=["markdown.extensions.extra", # "markdown.extensions.codehilite", # "markdown.extensions.toc", ], # output_format="html") md = Markdown( extensions=["markdown.extensions.extra", "markdown.extensions.codehilite", "markdown.extensions.toc", ], output_format="html" ) # Convert markdown to serialized XHTML or HTML. post.body = md.convert(post.body) post.toc = md.toc return render(request,"blog/detail.html",context={ "post":post, "comments":comments, "form":form, })
右側(cè)導(dǎo)航欄
{# 基模板 #}
詳情頁添加博客目錄
{# blog/detail.html #} {% block toc %}{% endblock %}文章目錄
{{ post.toc | safe }}
按類別查找
按標(biāo)簽查找
按時(shí)間查找
顯示博客目錄分頁
Django提供了一個(gè)新的類來幫助你管理分頁數(shù)據(jù),這個(gè)類存放在django/core/paginator.py.它可以接收列表、元組或其它可迭代的對(duì)象。
def index(request): all_posts = Post.objects.count() if all_posts % PER_PAGE != 0: page_nums = all_posts // PER_PAGE + 1 else: page_nums = all_posts // PER_PAGE paginator = Paginator(Post.objects.all(),PER_PAGE) if request.GET.get("page"): page = request.GET.get("page") else: page = 1 try: posts = paginator.page(page) except (PageNotAnInteger,EmptyPage): posts = paginator.page(1) posts.has_previous() posts.has_next() posts.previous_page_number() posts.next_page_number() return render(request, "blog/index.html", context={ "title":"博客首頁", "posts":posts, "pages_num":page_nums, })
修改主頁的html文件有關(guān)分頁顯示的部分
{% if posts.has_previous %} 上一頁 {% else %} 上一頁 {% endif %} 第 {{ posts.number }} 頁 / 共 {{ pages_num }} 頁 {% if posts.has_next %} 下一頁 {% else %} 下一頁文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/42646.html
摘要:首發(fā)于我的博客線程池進(jìn)程池網(wǎng)絡(luò)編程之同步異步阻塞非阻塞后端掘金本文為作者原創(chuàng),轉(zhuǎn)載請(qǐng)先與作者聯(lián)系。在了解的數(shù)據(jù)結(jié)構(gòu)時(shí),容器可迭代對(duì)象迭代器使用進(jìn)行并發(fā)編程篇二掘金我們今天繼續(xù)深入學(xué)習(xí)。 Python 算法實(shí)戰(zhàn)系列之棧 - 后端 - 掘金原文出處: 安生??? 棧(stack)又稱之為堆棧是一個(gè)特殊的有序表,其插入和刪除操作都在棧頂進(jìn)行操作,并且按照先進(jìn)后出,后進(jìn)先出的規(guī)則進(jìn)行運(yùn)作。 如...
摘要:本教程內(nèi)容已過時(shí),更新版教程請(qǐng)?jiān)L問博客開發(fā)入門教程。當(dāng)分頁較多時(shí),總是顯示當(dāng)前頁及其前幾頁和后幾頁的頁碼教程中使用的是兩頁,其他頁碼用省略號(hào)代替。 本教程內(nèi)容已過時(shí),更新版教程請(qǐng)?jiān)L問: django 博客開發(fā)入門教程。 摘要:前兩期教程我們實(shí)現(xiàn)了博客的 Model 部分,以及 Blog 的首頁視圖 IndexView,詳情頁面 DetailView,以及分類頁面 CategoryVi...
閱讀 2784·2023-04-25 18:06
閱讀 2576·2021-11-22 09:34
閱讀 1684·2021-11-08 13:16
閱讀 1302·2021-09-24 09:47
閱讀 3049·2019-08-30 15:44
閱讀 2773·2019-08-29 17:24
閱讀 2584·2019-08-23 18:37
閱讀 2433·2019-08-23 16:55
發(fā)表評(píng)論
評(píng)論列表,共 {{ comments.count }} 條評(píng)論
{% for comment in comments %}-
{{ comment.user }}
{{ comment.text }}
{% endfor %}