上一章https://blog.51cto.com/yht1990/2382801
本章节官网详细参考:https://docs.djangoproject.com/zh-hans/2.1/intro/tutorial02/
1、配置pymysql代替MySQLdb
在需要的项目中(D:\mysite\polls下的init.py)添加如下内容
import pymysql
pymysql.install_as_MySQLdb()
2、服务器创建mysite数据库,配置权限允许访问数据库的IP
3、配置允许所有主机访问
mysite\settings.pyALLOWED_HOSTS = ["*"]
4、数据库配置
mysite\settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysite',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '192.168.20.217',
'PORT': '3306',
}
}
5、配置包含应用
mysite\settings.py
INSTALLED_APPS = [
'polls.apps.PollsConfig', #添加的配置
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
6、注释csrf验证
mysite\settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
7、创建存放静态html文件目录,所有静态文件放此目录下
即建一个templates再建polls
8、创建存放bootstarp文件目录,所有boostarp文件放此目录下
即建一个static再建polls
9、创建模型
polls/models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
10、建表
1)为模型的改变生成迁移文件。
D:\mysite>python manage.py makemigrations
Migrations for 'polls':
polls\migrations\0001_initial.py
- Create model Choice
- Create model Question
- Add field question to choice
2)开始建表python manage.py migrate
2) 向管理页面加入投票应用
polls/admin.py
from django.contrib import admin
from .models import Question
admin.site.register(Question)
3)重启访问
ide重启项目,访问:http://127.0.0.1:8000/admin/