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中

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐