我的博客开发(001)
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class BlogType(models.Model):
type_name = models.CharField(max_length=15)
def __str__(self):
return self.type_name
class Blog(models.Model):
title = models.CharField(max_length=50)
blog_type = models.ForeignKey(BlogType,on_delete=models.DO_NOTHING)
content = models.TextField()
author = models.ForeignKey(User,on_delete=models.DO_NOTHING)
created_time = models.DateTimeField(auto_now_add = True)
last_updated_time = models.DateTimeField(auto_now=True)
def __str__(self):
return "" % self.title
blog/views.py
from django.shortcuts import render,get_object_or_404
from .models import Blog,BlogType
# Create your views here.
def blog_list(request):
context = {}
context['blogs'] = Blog.objects.all()
# 用于统计博客数量作为一个值放在字典context中,然后其键是blogs_count
# context['blogs_count'] = Blog.objects.all().count()
return render(request,"blog_list.html",context)
def blog_detail(request,blog_pk):
context = {}
context['blog'] = get_object_or_404(Blog,pk=blog_pk)
return render(request,"blog_detail.html",context)
def blogs_with_type(request,blog_type_pk):
context = {}
blog_type = get_object_or_404(BlogType,pk=blog_type_pk)
context["blogs"] = Blog.objects.filter(blog_type=blog_type)
context['blog_type'] = blog_type
return render(request,'blogs_with_type.html',context)
mysite/urls.py
from django.contrib import admin
from django.urls import path,include
from blog.views import blog_list
# from ..blog.views import blog_list
urlpatterns = [
path('',blog_list,name="home"), # 首页
path('admin/', admin.site.urls),
path('blog/',include('blog.urls')),
]
blog/urls.py
from . import views
from django.urls import path
urlpatterns = [
# http://localhost/8000/blog/1
path('', views.blog_detail, name="blog_detail"),
# http://localhost:8000/blog/ 博客列表地址
path('type/',views.blogs_with_type,name="blogs_with_type"),
]
blog_detail.html
{{blog.title}}
{{blog.title}}
作者:{{ blog.author }}
{# 这里为啥标红?另外这里年月日时分秒和Python的datetime中有点不一样,在分钟那html用n表示!H表示24进制小时,h表示12进制 #}
发表日期:{{ blog.created_time|date:"Y-m-d H:n:s" }}
{{blog.content}}
blog_list.html
刘子君的博客
{% for blog in blogs %}
{# #}
{{blog.title}}
{# 管道符表示过滤,这句话意思是对blogcontent中的内容过滤,只剩30字符显示,这里不知为啥起作用了但pycharm识别为错误#}
{{ blog.content|truncatechars:30 }}
{% empty %}
----- 敬请期待,暂无博文 -----
{% endfor %}
{# 一共有{{ blogs|length }}篇博文
{{ blogs_count }} {# 用于统计blogs中又多少条博文#}
一共有{{ blogs|length }}篇博文
blogs_with_type.html
刘子君的博客
{% for blog in blogs %}
{# #}
{{blog.title}}
{# 管道符表示过滤,这句话意思是对blogcontent中的内容过滤,只剩30字符显示,这里不知为啥起作用了但pycharm识别为错误#}
{{ blog.content|truncatechars:30 }}
{% empty %}
----- 敬请期待,暂无博文 -----
{% endfor %}
{# 一共有{{ blogs|length }}篇博文
{{ blogs_count }} {# 用于统计blogs中又多少条博文#}
一共有{{ blogs|length }}篇博文
答疑:
# blog_list.html
{# 管道符表示过滤,这句话意思是对blogcontent中的内容过滤,只剩30字符显示,这里不知为啥起作用了但pycharm识别为错误#}
{{ blog.content|truncatechars:30 }}