学会用Django框架实现功能(一)
1. 理解MTV模型
1.1 自己画的一张很丑的草图
Models:artificial_satellite::模型层,数据代理人,使用python的方法操作数据库
Templates:athletic_shoe::模板层,将从models中取出来的数据填充到网页中,变成我们所看到的成形的网页(渲染)
Views:biking_woman::视图层,把渲染好的网页返回给用户
URLS:arrow_double_down::找到对应的处理某流程的view
2. 实现第一个Django网站
2.1 创建Django project
cd /Users/Hou/Desktop/root
django-admin startproject project名
#当然如果你跟我一样使用pychram创建项目的话,这一步就免了
2.11 manage.py 改为 python3
#!/usr/bin/env python3
如果电脑上有py2,py3两个版本,改为python3可以选择python3版本
2.2 创建Django App
python manage.py startapp firstapp(app名称)
#如果你想了解有哪些命令可以使用,可以输入
python manage.py help
2.3 setting 里增加app
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'firstapp' #新增这个,也就是你的django app的名字
]
2.4 模板层操作,html,css,js等文件
创建static文件夹,把css,js,图片放入
html文件放到templates文件夹中
2.4.1 在settings.py 里修改路径
STATIC_URL = '/static/'
#参考templates[]定义路径的写法
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
2.4.2 在html(index.html)中增加模板标签
2.4.3 views.py
def index_html(request):
return render(request, 'index_html')
2.4.4 urls.py
from get_app.views import index_html
urlpatterns = [
path('index/', index_html, name='index_html'),
]
2.4.5 运行服务器
python3 manage.py runserver
打开浏览器输入http://127.0.0.1:8000/ or http://localhost:8000/就会看到你的Django网站已经在web server上成功运行了
注意这里并不需要理会model层的东西,因为这里主要是看一下html的样式是否丢失,确保最基础的配置是正确的
2.5 创建数据库
2.5.1 合并、运行数据库
python3 manage.py makemigrations
python3 manage.py migrate
2.6 创建后台和超级管理员
2.6.1 建立管理员账号
python manage.py createsuperuser
# 按要求设置用户名和密码,最后看到successful就成功了
2.6.2 使用管理后台
执行runserver指令后,进入http://127.0.0.1:8000/admin登录
2.7 在Model中创建数据表
2.7.1 models.py
class People(models.Model):
# null表示数据库可以没有数据;
# blank名字什么都不填也没有问题;
# max_length长度不超过200
name = models.CharField(null=True, blank=True,
max_length=200)
job = models.CharField(null=True, blank=True,
max_length=200)
#admin后台中数据名称显示为name
def __str__(self):
return self.name
2.7.2 合并数据库
python3 manage.py makemigrations
python3 manage.py migrate
#每次model层有改动都要输入这两行合并数据库,切记切记
2.7.3 在admin中增加想要的后台管理数据(admin.py)
from firstapp.models import People
admin.site.register(People) #要有这一步操作才能在后台看到你在models.py中定义的东西
- 这样你就可以在后台手动添加一些数据了
2.8 在View中获取Model中的数据
引用model中写好的文章列表,然后去渲染文章列表
from firstapp.models import People, Article #引入People。。。
def index(request):
article_list = Aritcle.objects.all()
context = {
'article': article_list
}
return render(request, 'index.html', context)
2.9 在Template中增加动态内容
# article为view中context的'article'
2.10 在URL中分配网址(urls.py)
path('index/', index_html, name='index_html'),