1、 创建项目mydemo和应用myapp
django-admin startproject mydemo2
cd mydemo
dir
python manage.py startapp myapp
python manage.py runserver
2、连接数据库
1、进入Navicat,创建一个数据库mytest2, 2、通过执行表迁移创建数据库表 2.1 执行数据库的连接配置,网站配置 编辑mydemo2/mydemo2/settings.py文件
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
#配置模板路径信息
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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',
],
},
},
]
#数据库的连接
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mytest',
'USER': 'root',
'PASSWORD': '125358',
'HOST': 'localhost',
'PORT': '3306',
}
4、定义model类
4.1编辑mydemo2/myapp/models.py
from django.db import models
from datetime import datetime
class Users(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField(default=20)
phone = models.CharField(max_length=16)
addtime=models.DateTimeField(default=datetime.now)
4.2 生成迁移文件
python3 manage.py makemigrations
4.3、执行迁移
python manage.py migrate
此时数据库中会有一张表,并且有字段
4.4、在myapp/views.py中配置首页
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse('首页')
4.5、配置路由
在总urls.py中
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path("",include('myapp.urls'))
]
在myapp下创建子路由urls.py
from django.urls import path
from . import views
urlpatterns = [
path("",views.index,name='index'),
]
在命令窗口启动服务,可以看到如下界面
5、操作数据库数据
from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import Users
def index(request):
mod = Users.objects
ulist = mod.order_by('age')[:3]
for u in ulist:
print(u.id,u.name,u.age)
return HttpResponse('首页')
参考:https://www.bilibili.com/video/BV1pq4y1W7a1?p=10
|