git clone https://github.com/ django/ django.git 【github写的源码,仅供参考】
创建项目的2种命令:
python manage.py startapp blog #注册应用
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' # 上海时区
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 迁移数据
python manage.py createsuperuser # 新建超级管理员
设置账户,邮箱,密码。
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中