1、安装,指定安装2.2版本

pip install django==2.2 -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
2、创建测试项目
django-admin.py startproject testDjango
cd testDjango
python manage.py runserver
生成目录结构如下

目录结构说明:
testDjango: 项目的容器。
manage.py: 一个实用的命令行工具,可让你以各种方式与该 Django 项目进行交互。
testDjango/init.py: 一个空文件,告诉 Python 该目录是一个 Python 包。
testDjango/settings.py: 该 Django 项目的设置/配置。
testDjango/urls.py: 该 Django 项目的 URL 声明; 一份由 Django 驱动的网站"目录"。
testDjango/wsgi.py: 一个 WSGI 兼容的 Web 服务器的入口,以便运行你的项目。
访问地址为http://127.0.0.1:8000

修改默认视图,在testDjango项目下创建一个Index.py文件,并输出This is my first django project,这里我们需要使用django的http模块的httpresponse函数坐输出渲染
Index.py文件
from django.http import HttpResponse
def index(request):
return HttpResponse("This is my first django project")
urls.py文件
from django.urls import path
from . import Index
urlpatterns = [
path('', Index.index),
]
访问效果如图

urls或者添加path
from django.urls import path
from . import Index
urlpatterns = [
path('index/', Index.index),
]
访问的时候加index路径

3、django可以包含多个模块,创建后台管理模块
python manage.py startapp sysadmin
执行上面的命令会在当前路径下创建admin目录,其目录结构如下所示:
init.py:一个空文件,告诉Python解释器这个目录应该被视为一个Python的包。
admin.py:可以用来注册模型,用于在Django的管理界面管理模型。
apps.py:当前应用的配置文件。
migrations:存放与模型有关的数据库迁移信息。
init.py:一个空文件,告诉Python解释器这个目录应该被视为一个Python的包。
models.py:存放应用的数据模型,即实体类及其之间的关系(MVC/MTV中的M)。
tests.py:包含测试应用各项功能的测试类和测试函数。
views.py:处理请求并返回响应的函数(MVC中的C,MTV中的V)。
sysadmin模块下创建views.py视图
from django.http import HttpResponse
def view(res):
return HttpResponse("<h1> At such a time of crisis,we must try to set aside all differences and stick together")
在新模块下创建url映射匹配规则,urls.py,path不填表示默认访问路径为根路径
from django.urls import path
from . import views
urlpatterns = [
path('', views.view)
]
4、接下来对新模块的url在项目中进行合并,在项目下urls.py使用include进行合并,sysadmin代表模块
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.view),
path('sysadmin/',include('sysadmin.urls') )
]

访问效果如下图

4、使用django模板显示
在sysadmin模块下创建list视图view.py
from django.shortcuts import render
dict_words = [
{'word': 'diversity', 'meaning': 'the diversity of something is the fact that it contains many very different elements', 'eg': 'the cultural diversity of british society'},
{'word': 'antique', 'meaning': 'something made in an earlier period that is collected and considered to have value because it is beautiful, rare, old, or high quality', 'eg': 'My mother collects antique'},
{'word': 'stuff', 'meaning': 'You can use stuff to refer to things such as a substance, a collection of things, events, or ideas', 'eg': ' do not tell me you still believe in all that stuff'},
]
def sysadmin(res):
return render(res, 'word.html', {'dict_words': dict_words})
在模块创建跳转入口,urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.sysadmin)
]
在项目下创建templates模板目录

<h1>This is word page</h1>
<table>
<tr>
<th>word</th>
<th>meaning</th>
<th>eg</th>
</tr>
{% for word in dict_words%}
<tr>
<td>{{word.word}}</td>
<td>{{word.meaning}}</td>
<td>{{word.eg}}</td>
</tr>
{% endfor %}
</table>
在项目下urls.py合并url
from django.urls import path, include
from . import view
urlpatterns = [
path('', view.index),
path('sysadmin/', include('sysadmin.urls'))
]
最后修改项目的默认模板设置,将创建的templates目录添加到里面来

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',
],
},
},
]
最后启动效果如果

6、数据库操作
安装数据库模块
pip install -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com pymysql
在项目下init文件加入初始化数据库代码
import pymysql
pymysql.install_as_MySQLdb()
在setting文件配置数据库

创建数据库
create database lw_word default charset utf8;
新建模块并注册到app

pip卸载软件
pip uninstall name
在models文件定义model模型,
from django.db import models
class Article(models.Model):
article_id = models.AutoField(primary_key=True)
title = models.TextField()
brief_content = models.TextField()
content = models.TextField()
publish = models.DateTimeField(auto_now=True)
生成迁移文件
python manage.py makemigrations
同步到数据库
python manage.py migrate
数据库建表完成

7、使用django shell 插入数据
python manage.py shell 进入django shell

from blog.models import Article
article = Article()
article.title = 'blog'
article.brief_content = 'provide sb for sth'
article.content = 'provide sb for sth'
article.save()
获取数据库的数据
articles = Article.objects.all()
article = articles[0]
article = articles[2]
print(article.content)
说明数据插入成功
provide sb for sth
8、django admin 模块



创建超级管理员账号。
source-shell
(venv)$ python manage.py createsuperuser
Username (leave blank to use 'tk'):tk
Email address: tk@qq.com
Password:
Password (again):
Superuser created successfully.
启动Web服务器,登录后台管理系统。
source-shell
(venv)$ python manage.py runserver
访问[http://127.0.0.1:8000/admin](http://127.0.0.1:8000/admin),会来到如下图所示的登录界面。

登录后进入管理员操作平台。

至此我们还没有看到之前创建的模型类,需要在应用的admin.py文件中模型进行注册。
注册模型类。
(venv)$ vim blog/admin.py
from django.contrib import admin
from .models import Article
admin.site.register(Article)
注册模型类后,就可以在后台管理系统中看到它们。

打开具体对象可以查看对象属性信息,并更改

网页添加Article对象


可以看到新增的Article

为了更好的查看模型数据,可以为Article模型类添加str魔法方法。


响应数据到前端
如果查询数据提示没有objects属性,需要开启django支持

python如果导入不了自定义包,需要设置pycharm将当前项目定义为root目录

在blog增加视图渲染
from django.http import HttpResponse
from .models import Article
import json
Create your views here.
def blog_content(request):
articles = Article.objects.all()
article = articles[0]
title = article.title
brief_content = article.brief_content
content = article.content
id = article.article_id
date = article.publish
st = 'title: %s brief_contet: %s content: %s id %s date %s' %(title, brief_content, content, id, date)
return HttpResponse(st)
在blog应用注册path

在项目下注册path

网友评论