Django(Python Web框架)学习(二)快速入门
官方网址:https://www.djangoproject.com/
#在线安装Django,指定版本安装,可以根据自己的需求安装匹配的版本,我在这里安装的是Django2.2版本,
#安装命令如下:
pip install django==2.2
注:如果你是在Pycharm中第一次新建Django项目的话,会出现如下的界面:
如果网络良好,会安装成功,但也会比较耗时,如果网络不良好,直接会提示安装失败,另外,这种情况下安装的Djange默认会安装最新版本的,可能与要做的项目不匹配,会出现问题,如何解决呢:
如果网络良好并且已经安装成功,那么就在命令行先卸载:pip uninstall Django,然后再重新安装:pip install Django==2.2,即可。
如果创建项目时安装失败了,那么就直接在命令行执行命令:pip install Django==2.2,就可以。
我这里安装过了,再次安装就会提示安装过了。
django-admin startproject BookManage
python3 manage.py startapp bookApp
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return HttpResponse("欢迎进入图书管理系统!")
# bookApp/urls.py
from django.conf.urls import url
from . import views
# /post/1/
urlpatterns = [
url(r'^$', views.index, name='index'),
# ^: 以什么开头, $是以什么结尾。 [0-9]指单个数字, +代表前面的字符出现1次或者多次。
# [0-9]+: 1, 2, 2344, 78888,
# (?P[0-9]+) 关键字匹配
# /post/1/ ====> 1满足正则规则的, 将id=1
url(r'^post/(?P[0-9]+)/$', views.detail, name='detail')
]
# BookManage/urls.py
from django.conf.urls import url
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
# 当用户访问的url地址以book开头, 请访问bookApp.urls这个url配置文件进行匹配并执行对应
的视图函数.
url(r'^book/', include('bookApp.urls')),
]
$ python3 manage.py runserver
MariaDB [(none)]> create database BookManage charset=utf8;
# .......
# 注释之前的sqlite数据库;
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
# 添加新的Mysql数据库连接;
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'BookManage',
'USER': 'root',
'PASSWORD': 'westos',
'HOST': 'localhost',
'PORT': '3306',
}
}
# .......
$ pip install pymysql
import pymysql
# MySQLdb只支持Python2.*,还不支持3.可以用PyMySQL代替。
pymysql.install_as_MySQLdb()
# bookApp/models.py
from django.db import models
# Create your models here.
class Book(models.Model):
# 定义属性:默认主键自增id字段可不写
title = models.CharField(max_length=20)
pub_date = models.DateTimeField()
# 定义默认输出格式
def __str__(self):
return "%d" % self.title
# 自定义对应的表名,默认表名:bookApp_book
class Meta:
db_table = "books"
class Hero(models.Model):
name = models.CharField(max_length=20)
gender = models.BooleanField()
content = models.CharField(max_length=100)
Book = models.ForeignKey('Book', on_delete=False)
def __str__(self):
return "%s" % self.name
# 自定义对应的表名,默认表名:bookApp_hero
class Meta:
db_table = "heros"
# BookManage/settings.py
# Application definition
INSTALLED_APPS = [
# .......此处省略
'django.contrib.staticfiles',
# 新添加的app
'bookApp',
]
python manage.py makemigrations
python manage.py migrate
$ mysql -uroot -pwestos
MariaDB [(none)]> use BookManage
MariaDB [BookManage]> show tables;
MariaDB [BookManage]> desc books;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(20) | NO | | NULL | |
| pub_date | datetime | NO | | NULL | |
+----------+-------------+------+-----+---------+----------------+
MariaDB [BookManage]> desc heros;
+---------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| gender | tinyint(1) | NO | | NULL | |
| content | varchar(100) | NO | | NULL | |
| Book_id | int(11) | NO | MUL | NULL | |
+---------+--------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
python manage.py shell
from bookApp.models import Hero, Book
Book.objects.all()
from datetime import datetime
book = Book(title="射雕英雄传", pub_date=datetime(year=1990,month=1,day=10))
book.save()
book = Book.objects.get(pk=1)
book.id
book.title
book.pub_date
book.title = "天龙八部"
book.save()
book.delete()
# 书籍的创建
book = Book(title="倚天屠龙记", pub_date=datetime(year=1990,month=1,day=10))
book.save()
# 人物的创建
info1 = "峨眉第四代掌门人,先为峨眉派掌门灭绝师太的徒儿,颇获灭绝师太欢心并对她>青睐有加,将峨
眉派镇派之宝“蛾眉九阳功”传给了她,张无忌的追求者之一。"
info2 = "原名敏敏特穆尔,汝阳王(朝廷大将军察罕特穆尔)的女儿,封号“绍敏郡主”,>赵敏是她的汉
名,是从她的封号“绍敏郡主”而来。"
hero1 = Hero(name="周芷若", gender=False, info=info1)
hero2 = Hero(name="赵敏", gender=False, info=info2)
hero1.Book=book
hero2.Book=book
hero1.save()
hero2.save()
book.hero_set.create(name="张无忌",
gender=True,
content="武当派第二代“张五侠”张翠山与天鹰教紫微堂堂主殷素素的儿子")
python manage.py makemigrations
python manage.py migrate
# 按提示输入用户名、邮箱、密码
python manage.py createsuperuser
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
from django.contrib import admin
from models import Book
admin.site.register(Book)
# bookApp/models.py
class Book(models.Model):
# ........此处省略
# 自定义对应的表名,默认表名:bookApp_book
class Meta:
db_table = "books"
# 单数时显示的名称
verbose_name = '图书信息'
# 复数时显示的名称
verbose_name_plural = '图书信息'
# bookApp/admin.py
from django.contrib import admin
from .models import Book, Hero
# 书籍自定义管理页面
class BookAdmin(admin.ModelAdmin):
list_display = ['pk', 'title', 'pub_date']
list_filter = ['title']
search_fields = ['title']
list_per_page = 10
# fields = ['pub_date', 'title']
fieldsets = [('基础信息', {'fields': ['title']}),
('详细信息', {'fields': ['pub_date']}), ]
# 人物自定义管理页面
class HeroAdmin(admin.ModelAdmin):
list_display = ['id', 'name', 'gender', 'content']
list_filter = ['name']
search_fields = ['name']
list_per_page = 10
# 关联注册
admin.site.register(Book, BookAdmin)
admin.site.register(Hero, HeroAdmin)
list_display = ['pk', 'title', 'pub_date']
list_filter = ['title']
search_fields = ['title']
list_per_page = 10
# bookApp/models.py
class Hero(models.Model):
# .......此处省略部分重复代码
def sex(self):
if self.gender:
return "男"
else:
return "女"
# BookManage/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
# 当用户访问的url地址以book开头, 请访问bookApp.urls这个url配置文件进行匹配并执行对应
的视图函数.
url(r'^book/', include('bookApp.urls')),
]
# bookApp/urls.py
urlpatterns = [
# 当用户访问bookApp应用的主页时, 执行视图函数index,反向根据名称获取url地址;
url(r'^$', views.index, name='index'),
# 显示书籍的详情页
url(r'^([0-9]+)/$', views.detail, name='detail'),
]
# bookApp/views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("图书管理系统")
def detail(request, id):
return HttpResponse("图书管理详情页信息 %s" % id)
from django.shortcuts import render
from django.http import HttpResponse
from bookApp.models import Book
def index(request):
booklist = Book.objects.all()
return render(request, 'book/index.html', {'booklist': booklist})
# return HttpResponse("图书管理系统")
def detail(request, id):
book = Book.objects.get(pk=id)
return render(request, 'book/detail.html', {'book': book})
# return HttpResponse("图书管理详情页信息 %s" % id)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 修改的部分,指定模板路径
'DIRS': [os.path.join(BASE_DIR, 'templates')],
# ..................
},
]
(2) 模板语法: 变量
{ { var } }
{ % tag % }
{% for ... in ... %}
循环逻辑
{% endfor %}
if标签
{% if ... %}
逻辑1
{% elif ... %}
逻辑2
{% else %}
逻辑3
{% endif %}
comment标签
{% comment %}
多行注释
{% endcomment %}
include标签
{% include "base/left.html" %}
url :反向解析
{% url 'name' p1 p2 %}
csrf_token 标签
{% csrf_token %}
首页
图书列表
{% for book in booklist %}
- {
{ book.title }}
{% endfor %}
详细页
{
{ book.title }}
{% for hero in book.hero_set.all %}
- {
{ hero.name }}---{
{ hero.sex }}----{
{ hero.content }}
{% endfor %}