第一步.创建django
方法一:django-admin startproject
方法二: 直接在python上创建
第二步:创建工程名cmdb
python manage.py startapp cmdb(文件名)
第三步:设置静态文件路径
project.settings.py 文件中
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
第四步: 模板路径(在python中直接默认)不用设置
5.setting 中
middlerware
#注释csrf
6.定义路由规则
在url.py 中实现
如添加
from cmdb import views
url(r'^login/', views.login),
7.定义视图函数
在views.py
def func(request):
# request 表示接受的数据
request.method: GET/POST
request.POST.get("xxx", None)
return HttpResponse('字符串')
return render(request, HTML名字)
return redirect(HTML路径)
8.渲染模板
特殊的模板语言
{{变量名}}
def func(request):
return render(request, 'index.html', {'user_list': 'alex'})
for 循环
{%for row in user_list%}
<tr>
<td>{{user_list.username}}</td>
<td>{{user_list.email}}</td>
<tr>
{%endfor %}
if 条件语句
{%if %}
{%else%}
{%endif%}
一个功能实现一个登录页面和后台人员的添加删除功能
1.删除功能通过创建一个input标签和赋予按钮submit功能实现
登录功能主要通过redirect('/home/')重新传递数据
通过request.POST.get("xxx", None)获得重新传递的数据 xxx表示name属性的值
再次通过render传递
首先是setting文件
""" Django settings for 微博 project. Generated by 'django-admin startproject' using Django 2.0.7. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o)#wj+p-uo&!#g!iu#a_+yk5q8y1mr*u3i29ndfdb7#=@v$y3u' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = '微博.urls' 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', ], }, }, ] WSGI_APPLICATION = '微博.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )
url文件
"""微博 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ 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), url(r'^home/', views.home) ]
views 文件
from django.shortcuts import render from django.shortcuts import redirect # Create your views here. def login(request): if request.method == 'POST': error_msg = [] if request.POST.get('user', None)== 'root' and request.POST.get('pwd', None) == '123': return redirect('/home/') #跳转到/home/网络地址 else: error_msg = '请输入正确账号和密码' render(request, 'login.html', {'error_msg': error_msg}) return render(request, 'login.html') def home(request): List_dict = [{'usename': 'eric', 'email': '123456@qq.com', 'gender':'男'}, {'usename': 'alex', 'email': '123456@qq.com', 'gender': '男'}, {'usename': '小明', 'email': '123456@qq.com', 'gender': '男'},] list_dict = [] if request.method == 'POST': print(request.POST) print(request.method) print('1') x = request.POST.get('user') #获得值 print(x) for X in List_dict: if X['usename'] == x: pass else: list_dict.append(X) return render(request, 'home.html', {'List_dict': list_dict}) # u = request.POST.get('username',None) # print(u) # e = request.POST.get('email', None) # g = request.POST.get('gender', None) # tag = {'usename': u, 'email': e, 'gender':g} # List_dict.append(tag) return render(request, 'home.html',{'List_dict': List_dict})
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/commons.css"> <style> label{ width: 70px; display: inline-block; } </style> </head> <body> <form action="/login/" method="post"> <p> <label for = 'usename'>用户名:</label> <input id='usename' type="text" name="user" placeholder="用户名"> </p> <p> <label for="password">密码:</label> <input id='password' type="password" name="pwd" placeholder="密码"> <input type="submit" value="提交"> <span style="color: red">{{error_msg}}</span> </p> </form> </body> </html>
home.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .tb{ } .t1{ } .f1{ color:white; border: 0; } .f2{ color:white; border: 0; } .shadow{ background-color: black; position: fixed; left: 0; right: 0; bottom: 0; top: 0; opacity: 0.6; z-index: 9; } .hide{ display: none; } .media{ position: fixed; top: 50%; left: 50%; margin-left: -200px; margin-top: -200px; background-color: white; z-index: 10; height: 400px; width: 400px; } .la{ display: inline-block; width: 70px; } </style> </head> <body> <div id='s1' class="shadow hide"></div> <div id='m1' class="media hide"> <P> <label for='u1' class="la">用户名:</label> <input id='u1' type="text"> </P> <P> <label for='u2' class="la">密码:</label> <input id='u2' type="text"> </P> <P> <input id='u3' type="button" value="取消"> </P> </div> <table> {% for tag in List_dict %} {# L 循环为reden 的参数#} {# for循环#} <tr> <td class='t1' id="1" >{{ tag.usename }}</td> <td >{{ tag.email }}</td> <td >{{ tag.gender }}</td> <td> <form class="f1" action="/home/" method="post"> <input type="button" value="删除" class="tb"> </form> </td> <td><input type="button" value="详细信息" id="i3"></td> {% endfor %} </tr> <form action="/home/" method="post"> <input type="text" name="username" placeholder="用户名"> <input type="text" name="email" placeholder="邮箱"> <input type="text" name="gender" placeholder="性别"> <input type="submit" value="添加"> </form> </table> <script src="../static/jquery-2.12.4.js"></script> <script> $('.tb').click(function () { console.log(this); tag = $(this).parent().parent().parent().find("[id='1']").text(); input1 = document.createElement('input'); //创建input标签并且添加 input1.setAttribute('name', 'user'); input1.setAttribute('type', 'text'); $(input1).addClass('f2'); console.log(tag); input1.setAttribute('value', tag); console.log(input1); $(this).after(input1); $(this).parent().submit(); //使得button标签也具有跳转功能 {# console.log($(this).parent().parent().parent().find(".t1"));#} {##} {# #} {# $(this).val(tag);#} {# this.setAttribute('name', 'user');#} {# console.log(this);#} {# document.getElementById('f1').submit();#} {# input1 = document.createElement('input');#} {##} {# input1 = $(this).parent().parent().find([id='1']);#} {# console.log(input1);#} {# input1.setAttribute('type','text');#} {# input1.setAttribute('name', 'i1');#} }); $('#i3').click(function () { $('#s1').removeClass('hide'); $('#m1').removeClass('hide'); }); $('#u3').click(function () { $('#s1').addClass('hide'); $('#m1').addClass('hide'); }) </script> </body> </html>