django

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


image.png

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

生成目录结构如下


image.png

目录结构说明:
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


image.png

修改默认视图,在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),
]

访问效果如图


image.png

urls或者添加path
from django.urls import path
from . import Index

urlpatterns = [
path('index/', Index.index),
]

访问的时候加index路径


image.png

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') )
]


image.png

访问效果如下图


image.png

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模板目录


image.png

<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目录添加到里面来


image.png

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',
],
},
},
]

最后启动效果如果


image.png

6、数据库操作
安装数据库模块
pip install -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com pymysql

在项目下init文件加入初始化数据库代码
import pymysql
pymysql.install_as_MySQLdb()

在setting文件配置数据库


image.png

创建数据库
create database lw_word default charset utf8;

新建模块并注册到app


image.png

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

数据库建表完成


image.png

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


image.png

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 模块


image.png

image.png

image.png

创建超级管理员账号。

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),会来到如下图所示的登录界面。
image.png
登录后进入管理员操作平台。
image.png
至此我们还没有看到之前创建的模型类,需要在应用的admin.py文件中模型进行注册。

注册模型类。

(venv)$ vim blog/admin.py
from django.contrib import admin

from .models import Article

admin.site.register(Article)
注册模型类后,就可以在后台管理系统中看到它们。
image.png

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


image.png

网页添加Article对象


image.png

image.png

可以看到新增的Article


image.png

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

image.png

image.png

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


image.png

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


image.png

在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


image.png

在项目下注册path


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,366评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,521评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,689评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,925评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,942评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,727评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,447评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,349评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,820评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,990评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,127评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,812评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,471评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,017评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,142评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,388评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,066评论 2 355

推荐阅读更多精彩内容