首先,我们创建一个名为bookmanager的项目。命令行如下:
django-admin startproject bookmanager
接着,创建一个名为app01的APP,使用命令如下:
python manage.py startapp app01
然后,修改settings.py文件如下所示:
"""
Django settings for bookmanager project.
Generated by 'django-admin startproject' using Django 3.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '2a%la844cf!e9@q(+f3yf)7=@ahr5w7k_#0+pzur8_)_jsgcru'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config' # 加入app01
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware', # 注释掉csrf
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'bookmanager.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'bookmanager.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'bookmanager',
'HOST': '127.0.0.1',
'PORT': 3306,
'USER': 'root',
'PASSWORD': '123456'
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
当然了,也别忘记在__init__.py文件中加入下面的代码。
import pymysql
pymysql.install_as_MySQLdb()
好了,准备工作做完了。下面开始写models。
在models.py文件中添加下面的代码。
from django.db import models
# Create your models here.
class Publisher(models.Model):
name = models.CharField(max_length=128) # 出版社名称
然后迁移数据库,依旧是下面这两条命令。
python manage.py makemigrations
>python manage.py migrate
向数据库加入几条数据,例如:
在views.py文件中写API
from django.shortcuts import render
from app01 import models
# Create your views here.
def publisher_list(request):
obj = models.Publisher.objects.all() # 获取所有对象
return render(request, 'publisher_list.html', {'publisher_list': obj}) # {'publisher_list': obj}是模板,可以传递给前端页面。
然后在urls.py中写路由
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('publisher_list/', views.publisher_list),
]
publisher_list.html文件内容如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>序号</th>
<th>id</th>
<th>出版社名称</th>
</tr>
</thead>
<tbody>
{% for i in publisher_list %} <!-- for循环来显示出版社 -->
<tr>
<td>{{ forloop.counter }}</td> <!-- 循环计数 -->
<td>{{ i.id }}</td> <!-- 取出id -->
<td>{{ i.name }}</td> <!-- 取出出版社名字 -->
</tr>
{% endfor %} <!-- 结束for循环 -->
</tbody>
</table>
</body>
</html>
写完这些以后,运行项目。可以得到如下的页面。