django1.8.2版本连接sqlite数据库
一、创建djnago项目
file------new project


创建完毕

验证是否成功,运行


二、创建app
#如果怕命令打错,可以先执行python manage.py
python manage.py startapp myapp #会在根目录下出现一个myapp文件夹


三、配置settings.py
settings.py中注册app
INSTALLED_APPS = (
...,
'myapp',
)

检查settings.py是否有配置templates的路径(我这儿创建django项目时就已经生成,无需再配置)

四、写一个页面
第一步:myapp/views.py定义视图(用上V)
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("这是一道白切鸡!!!!!!!!")
第二步:blog/urls.py中注册视图(路由)
from django.conf.urls import include, url
from django.contrib import admin
from myapp.views import index
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^index/', index,name='index'),
]
第三步:项目重启后访问

五、美化页面(用上T)
第一步:templates定义模板
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 style="background-color:greenyellow">这是一道白切鸡!!!!</h1>
</body>
</html>
第二步:修改myapp/views.py视图(用上V)
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
# return HttpResponse("这是一道白切鸡!!!!!!!!")
return render(request,'myapp/index.html')
第三步:项目重启后访问
127.0.0.1:8000/index/

六、连接数据库(sqlite3)
1.myapp/models.py定义模型
from django.db import models
class LoginUser(models.Model):
user_name=models.CharField(max_length=20)
desc=models.CharField(max_length=20)
2.terminal终端执行迁移命令
#第一步 生成迁移文件 (在项目文件中生成映射文件)
python manage.py makemigrations
#第二步 执行迁移(在数据库中生成表)
python manage.py migrate
如果修改、添加了字段,则需要重复以上两步完成数据库的迁移。


添加一个字段
from django.db import models
class LoginUser(models.Model):
user_name=models.CharField(max_length=20)
desc=models.CharField(max_length=20)
# age=models.CharField(max_length=20)
age=models.CharField(max_length=20,default='')
执行迁移,出现如下

先选择2

打开navicat,连接sqlite3数据库


然后测试连接


输入一行
3.myapp.views.py中使用
from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import LoginUser
def index(request):
# return HttpResponse("这是一道白切鸡!!!!!!!!")
# return render(request,'myapp/index.html')
user=LoginUser.objects.first()
return render(request,"myapp/index.html",context={'user':user})
4.templates/mapp/index.html中渲染
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
名字:<h1>{{user.user_name}}</h1>
描述:<h1>{{user.desc}}</h1>
年龄:<h1>{{user.age}}</h1>
<hr>
<h1 style="background-color:greenyellow">这是一道白切鸡!!!!</h1>
</body>
</html>
5.项目重启后访问url

修改数据库内容

刷新浏览器

django3.xx和4.xx版本连接sqlite数据库
其他内容同上
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path("admin/", admin.site.urls),
path("index/", views.index),
]
项目重启访问
