编程环境
Google浏览器
致网OpenLAB网络实验平台
安装Django框架
1、打开python控制台,检查有无安装django框架
1 pip install django -i https://pypi.douban.com/simple/
创建Django工程项目 1 django-admin startproject webDemo
创建Django的blog app 1 django-admin startapp zyb_blog
配置settings.py文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ALLOWED_HOSTS = ['*'] //允许所有ip的请求 # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'zyb_blog', //添加我的blog app ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', //取消跨站攻击保护,即注释掉此行代码 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
启动Django工程 1 python manage.py runserver 0.0.0.0:8090
新建一条你的url
1 2 3 4 5 6 7 8 from django.conf.urls import url from django.contrib import admin from zyb_blog import views //add urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^zyb_blog/',views.zyb_blog) //add ]
1 2 3 4 5 6 7 8 9 10 # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render # Create your views here. def zyb_blog(request): context = {} return render(request,'zyb_blog.html',context)
1 http://58.213.119.26:18080/api/v1/namespaces/web-ide/services/theia-ide-abb35e498637:web-8090/proxy/zyb_blog/
创建templates文件夹
1 2 3 4 5 6 7 8 <html> <head> </head> <body> <p>hello</p> </body> <html>
完善你的博客主页
在你的博客目录下新建static文件夹
,并在static文件夹
下新建img文件夹
和js文件夹
上传一个图片head.jpg
到img文件夹
,上传jquery-3.3.1.min.js
到js文件夹
3、修改主页文件zyb_blog.html
的标签,新增input
和textarea
标签
1 2 3 4 5 6 7 8 9 10 11 12 13 <html> <head> </head> <body> <div> <p>hello</p> <input id="title" type="text" placeholder="请输入标题"><br> <textarea id="context" cols="20" rows="20" placeholder="请输入内容"></textarea><br> <button id="submit_btn">发布内容</button> </div> </body> <html>
4、新建博客主页中相关控件所需的js文件zyb_blog.js
,并编辑内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 //监听button按钮 $('#submit_btn').on('click',function(){ var title = $('#title').val(); var context = $('#context').val(); var post_data = {"title":title,"context":context}; //获取input输入 console.log('HELLO zyb');//测试监听按钮是否正常 console.log(title); console.log(context); //新建ajax请求 $.ajax({ type: "POST", url: "zyb_blog/", data: post_data, success: function(data){ console.log('return success'); } }); });
5、修改views.py
文件,修改view函数
,接受post请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import JsonResponse # Create your views here. def zyb_blog(request): if request.method == "GET": context = {} return render(request,'zyb_blog.html',context) else: title = request.POST.get("title") context = request.POST.get("context") print(title) print(context) context = {"result": "success"} return JsonResponse(context)
6、修改zyb_blog.html
的文件,应用个性化zyb_blog.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 {% load static %} <html> <head> </head> <body> <div> <p>hello</p> <input id="title" type="text" placeholder="请输入标题"><br> <textarea id="context" cols="20" rows="20" placeholder="请输入内容"></textarea><br> <button id="submit_btn">发布内容</button> </div> </body> <html> <script src="/static/js/jquery-3.3.1.min.js"></script> <script src="/static/js/zyb_blog.js"></script>
7、修改主页文件zyb_blog.html
,新建博客主页头部head
,使用<img>
标签引用图片
1 <img src="/static/img/head.jpg">
1 2 3 4 5 6 7 8 9 10 //启动数据库 service mysql start //链接数据库 mysql -u root -popenlab //查看数据库 show databases; //创建数据库webDemo create database webDemo default charset utf8; //进入数据库 use webDemo;
9、配置Django工程
使用已创建的数据库:修改settings.py
文件连接数据库
1 2 3 4 5 6 7 8 9 10 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "webDemo", 'USER': "root", 'PASSWORD':"openlab", 'HOST':'127.0.0.1', 'PORT':'3306' } }
10、安装python操作mysql数据库
的包,指定国内源加速下载
1 root@theia-ide-abb35e498637-0:/home/openlab/workspace/webDemo# pip install mysqlclient -i https://pypi.douban.com/simple/
11、修改models.py
文件,在已有数据库中的创建表,保存所需数据(无需再进入MySQL中操作)
1 2 3 4 5 # Create your models here. class Table(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=128) context = models.TextField()
1 2 3 4 root@theia-ide-abb35e498637-0:/home/openlab/workspace/webDemo# python manage.py makemigrations //(Django语法)将刚刚在models.py中创建的表对象转换为数据库能够识别的SQL语句,接着将SQL语句刷到指定数据库中 root@theia-ide-abb35e498637-0:/home/openlab/workspace/webDemo# python manage.py migrate //migrate:迁移,将表从别的地方迁移至数据库中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import JsonResponse from models import Table //导入指定数据库中所需表 # Create your views here. def zyb_blog(request): if request.method == "GET": context = {} return render(request,'zyb_blog.html',context) else: title = request.POST.get("title") context = request.POST.get("context") print(title) print(context)//传到后端 table = Table(title=title,context=context) //写入函数,传入所需值 table.save() //保存传入值,如果获取到值,即传入zyb_blog_table表中 context = {"result": "success"} return JsonResponse(context)
1 2 3 4 5 6 7 8 9 10 $.ajax({ type: "POST", url: "zyb_blog/", data: post_data, success: function(data){ //console.log('return success'); location.reload(); } });
其他事项 重新启动Django
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 root@theia-ide-abb35e498637-0:/home/openlab/workspace# ls webDemo root@theia-ide-abb35e498637-0:/home/openlab/workspace# cd webDemo root@theia-ide-abb35e498637-0:/home/openlab/workspace/webDemo# python manage.py runserver 0.0.0.0:8090 Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. September 16, 2020 - 06:35:47 Django version 1.11.29, using settings 'webDemo.settings' Starting development server at http://0.0.0.0:8090/ Quit the server with CONTROL-C. [16/Sep/2020 06:35:51] "GET /zyb_blog/ HTTP/1.1" 200 480 [16/Sep/2020 06:35:51] "GET /static/js/jquery-3.3.1.min.js HTTP/1.1" 200 86927 [16/Sep/2020 06:35:51] "GET /static/js/zyb_blog.js HTTP/1.1" 200 444 [16/Sep/2020 06:35:51] "GET /static/img/head.jpg HTTP/1.1" 200 91084
数据库操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 mysql> show tables; +----------------------------+ | Tables_in_webDemo | +----------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | django_admin_log | | django_content_type | | django_migrations | | django_session | | zyb_blog_table | +----------------------------+ 11 rows in set (0.00 sec)
1 2 3 4 5 6 7 8 9 mysql> desc zyb_blog_table; +---------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | title | varchar(128) | NO | | NULL | | | context | longtext | NO | | NULL | | +---------+--------------+------+-----+---------+----------------+ 3 rows in set (0.00 sec)
1 2 mysql> select * from zyb_blog_table; Empty set (0.00 sec)