There are many Django, Tornado, Flask and other Python's WEB framework, Django compared to other WEB framework of its advantages: large and framework itself integrates the ORM, model binding, template engine, cache, Session, and many other functions. Today learn together under Django;
1. Preparations
Installation using pip: pip install Django
2. Basic Configuration
1) Create a program django
a command terminal:. django-admin startproject mysite, when creating IDE django program, these commands are executed essentially automatically
2) the directory structure is as follows:
3) configuration file - (settings.py)
a. Database
b. Templates
c. static files
3. Create App
a. command
python manage.py startapp cmdb
. B cmdb directory structure is as follows:
4. Log Examples
a. templates generated html file directory, such as login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <form action='/login/' method='POST'> <p> <input type="text" name="user" placeholder="用户名"/> </p> <p> <input type="password" name="pwd" placeholder="密码"/> </p> <p> 男:<input type="radio" name="sex" value="男"/> 女:<input type="radio" name="sex" value="女"/> </p> <p> <input type="submit" value="提交"/> </p> </form> </body> </html>
b. 修改url文件,定义路由规则
from django.contrib import admin from django.conf.urls import url from cmdb import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', views.login), ]
c. 定义视图函数:app下views.py
from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect # Create your views here. USER_LIST = {} def login(request): if request.method == 'GET': #判断请求方式 return render(request, 'login.html') elif request.method == 'POST': user = request.POST.get('user') #post请求,单选、输入框获取值 pwd = request.POST.get('pwd') sex = request.POST.get('sex') if user and pwd: USER_LIST['name'] = user USER_LIST['pwd'] = pwd USER_LIST['sex'] = sex return render(request, 'success.html', {"user_list": USER_LIST}) else: return HttpResponse('请求不能为空') else: return HttpResponse('请求方式不是get\post') #HttpResponse("字符串")
d. 提交成功后,跳转到success.html页面, hmtl模板获取 字典数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录成功页面</title> </head> <body> {{ user_list.name}} #获取字典中某个key的值 <ul> {% for k,v in user_list.items %} #循环字典 <li>{{ k }} : {{ v }}</li> {% endfor %} </ul> </body> </html>