老齐django实战第二版_博客开发笔记

1.博客系统

1.1.环境配置

  • python==3.6.5
  • django==2.1.4

git clone https://github.com/ django/ django.git 【github写的源码,仅供参考】

创建项目的2种命令:

  1. django-admin startproject mysite (常用)
  2. django-admin startproject mysite . (不常用,指在当前目录下创建)

1.2.注册app应用

python manage.py startapp blog    #注册应用

1.3.mysite/settings.py设置

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog'        # 添加应用
]
LANGUAGE_CODE = 'zh-hans'       # 中文
TIME_ZONE = 'Asia/Shanghai'     # 上海时区

1.4.mysite2/blog/models.py添加数据库模型

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User


class BlogArticles(models.Model):
    title = models.CharField(max_length=300)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ('-publish',)

    def __str__(self):
        return self.title

数据库迁移
python manage.py makemigrations 生成数据迁移文件
python manage.py migrate 迁移数据

1.5.新建超级管理员

python manage.py createsuperuser      # 新建超级管理员

设置账户,邮箱,密码。

1.5.1.然后在mysite2/blog/admin.py添加代码,关联到admin后台

from django.contrib import admin
from .models import BlogArticles           # models.py导入类将BlogArticles类引入到当前环境

class BlogArticlesAdmin(admin.ModelAdmin):
    list_display = ("title", "author", "publish")
    list_filter = ("publish", "author")
    search_fields = ("title", "body")
    raw_id_fields = ("author",)
    date_hierarchy = "publish"
    ordering = ['-publish', 'author']

admin.site.register(BlogArticles, BlogArticlesAdmin)   # 将该类注册到admin中

你可能感兴趣的:(python-Django,python,django)