如图所示创建目录结构:
1.模型的创建:
添加类别,标签,帖子三个模型,帖子模型外键连接user模型,多对一的关系;帖子模型外键连接category模型,多对一的关系;帖子模型连接tag模型,多对多的关系。
from django.db import models
# Create your models here.
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Tag(models.Model):
name = models.CharField(max_length=100)
#返回的内容会在后台上显示
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=70)
body = models.TextField()
created_time = models.DateTimeField(auto_now_add=True)
modified_time = models.DateTimeField(auto_now=True)
excerpt = models.CharField(max_length=200, blank=True, null=True)
views = models.PositiveIntegerField(default=0)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
#Tag.objects.filter(post=p)多对多可以通过小写类名传标签获取对象
tags = models.ManyToManyField(Tag, null=True, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
2.在blog.urls中添加首页路由:
添加首页路由,连接的是views.index视图函数,命名空间为’index’.
from django.conf.urls import url
from blog import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
3.在blog.urls中添加帖子列表的视图函数:
帖子列表的排序为按时间倒序排序,传入到模板的上下文环境是{‘post_list’: post_list}:
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from .models import Post
def index(request):
#帖子列表排序
post_list = Post.objects.all().order_by('-created_time')
return render(request, 'blog/index.html', context={'post_list': post_list})
4.在blog.admin中注册模型:
只有注册之后的模型才会在后台页面上显示出来,然后才能通过后台对模型进行操作。
from django.contrib import admin
# Register your models here.
from .models import Post, Category, Tag
admin.site.register(Post)
admin.site.register(Category)
admin.site.register(Tag)
5.代码运行之后显示的效果: