环境配置:win10+pycharm社区版+django2.2
目录
1.Django起步(简单的博客系统)
1.创建项目(注:为了准确说明目录或文件的位置,以下介绍以./表示项目根目录,如manage.py的位置为./manage.py)
首先规划好将项目创建在什么地方,并在cmd下进入到该目录,执行django-admin startproject mysite
其中1.mysite是项目名称;2.命令行输入django-admin可查看django-admin的常用用法
D:myprojectmysite>django-admin Type 'django-admin help <subcommand>' for help on a specific subcommand. Available subcommands: [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate runserver sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.).
创建好的项目目录结构如下:
启动项目:python manage.py runserver ,并访问http://127.0.0.1:8000/看到如下页面说明服务已正常启动
2.创建应用
python manage.py blog
创建应用后目录结构如下:
3.将应用注册到项目中
4.创建博客的数据库(后端开发)
编写数据模型类 ./blog/models.py
from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class BlogArticles(models.Model): title = models.CharField(max_length=300) author = models.ForeignKey(User, related_name='blog_posts',on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) class Meta: ordering = ("-publish",) def __str__(self): return self.title
将BlogArticles类注册到admin,编辑文件./blog/admin.py
from django.contrib import admin from blog.models import BlogArticles # Register your models here. admin.site.register(BlogArticles)
依次执行:python manage.py makegrations
python manage.py migrate
然后在pycharm中将文件db.sqlite拖到database区域,可以查看生成的表(这里我使用的默认数据库sqlite):
创建超级管理员:创建管理员后可以使用Django默认的管理功能发布文章。(这里我的用户名密码设为admin/test123456)
E:myprojmysite>python manage.py createsuperuser
Username (leave blank to use 'acer'): admin
Email address: wmm_0165@163.com
Password:
Password (again):
Superuser created successfully.
再次启动服务器python manage.py runserver ,访问http://127.0.0.1:8000/admin 登录系统
5.显示博客