设为首页 收藏本站
查看: 1041|回复: 0

[经验分享] Python Web框架Django学习(二)

[复制链接]

尚未签到

发表于 2018-8-9 12:54:08 | 显示全部楼层 |阅读模式
  python web框架Django学习(二)
  目录:
  三、Django创建APP
  四、创建登录页面,实现用户交互,后台管理用户(非数据库方式)
  
  =================================================================================================
  三、Django创建App
  =================================================================================================
  1、首先使用django-admin创建好一个django项目
  django-admin startproject test01
  2、在test01目录下面执行命令
  D:\python2.7.13\exercise\test01>python manage.py startapp cmdb     #app名称为cmdb
  D:\python2.7.13\exercise\test01>python manage.py startapp openstack
  3、查看目录(使用pycharm打开查看),确认是否创建成功!
DSC0000.png

  4、实现浏览器中访问项目cmdb
  1) 新创建的cmdb App中的目录有:
DSC0001.png

  2) 修改cmdb中的views.py文件,具体配置如下:
from django.shortcuts import render  
from django.shortcuts import HttpResponse  #加入
  

  
# Create your views here.
  
def home(request):                         #定义函数home
  
    return HttpResponse('<h1>这是我的第一个Django--App程序!!!<h1>')                        HttpResponse()
  3) 修改项目中的urls.py文件
  from django.conf.urls import url
  from django.contrib import admin
  from django.shortcuts import HttpResponse  #导入HttpServer模块
  import time                                #加入
  from cmdb import views                    #导入cmdb app中的views
  def home(request):                         #定义函数home
  return HttpResponse('<h1>这是我的第一个Django程序!!!<h1>')
  urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^index.html',home),           #添加index.html
  url(r'^cmdb',views.home),            #将cmdb app添加到url中
  ]
  4) 开启django服务器:
  5) 浏览器访问测试:
DSC0002.png

  ==================================================================================================
  四、创建登录页面,实现用户交互,后台管理用户(非数据库方式)
  =================================================================================================
  1、在项目test01目录下面创建一个templates目录,并且在templates目录中创建一个html文件index.html。
  2、在html文件中写入内容如下:
  <!DOCTYPE html>
  <html lang="en">
  <head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
  label{
  width: 120px;
  text-align: right;
  display: inline-block;
  }
  </style>
  </head>
  <body>
  <form action="/login" method="post">
  <p>
  <label for="username">请输入用户名</label>
  <input type="text" />
  </p>
  <p>
  <label for="password">请输入密码</label>
  <input type="text" />
  <input type="submit"  values="提交"/>
  </p>
  </form>
  </body>
  </html>
  3、在APP文件cmdb目录下的views.py文件中写入以下内容:
  from django.shortcuts import HttpResponse  #加入
  # Create your views here.
  def login(request):             #定义函数home
  f = open('templates/index.html','r',encoding='utf8')
  data = f.read()
  f.close()
  return HttpResponse(data)
  【注意】:可以将views.py中的以上内容修改为:
  from django.shortcuts import render
  def login(request):
  return render(request,'index.html')
  并且修改项目文件test01中的setting.py中的TEMPLATES中的DIRS,修改为
  'DIRS': [os.path.join(BASE_DIR,'templates')],
  表示默认模板位置在templates目录下面。
DSC0003.png

  4、在项目文件夹test01下面的urls.py文件中加入
  urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^index.html',home),           #添加index.html
  url(r'^login',views.login),            #将cmdb app添加到url中
  ]
  5、开启django服务器,浏览器访问效果为:
DSC0004.png

  到此,浏览器能够正常访问前端页面,但是不能实现用户交互!!!
  
  下面将实现用户输入正确的用户名和密码时跳转到百度首页;输入错误的用户名或者密码时,提示“用户名或密码错误”
  6、在app文件cmdb中的views.py中加入:
  from django.shortcuts import render
  from django.shortcuts import redirect
  def login(request):
  if request.method == "POST":
  user = request.POST.get('user',None) #得到用户输入的用户名
  pwd = request.POST.get('pwd', None)  #得到用户输入的密码
  print(user,pwd)               #在后台打印用户输入的用户名和密码
  if user == 'root' and pwd == '123456': #判断
  return redirect('http://www.baidu.com') #跳转到百度
  return render(request, 'index.html')
  当用户输入用户名为root,密码为123456时,跳转到百度首页!!!
  7、继续设计当用户输入错误信息是,返回“用户名或密码错误”
  1) 在index.html文件中加入一行:<span>` error_message `</span>
  加入后,index.html文件为:
  <!DOCTYPE html>
  <html lang="en">
  <head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
  label{
  width: 120px;
  text-align: right;
  display: inline-block;
  }
  </style>
  </head>
  <body>
  <form action="/login" method="post">
  <p>
  <label for="username">请输入用户名:</label>
  <input type="text" name="user"/>
  </p>
  <p>
  <label for="pwd">请输入密码:</label>
  <input type="password" name="pwd"/>
  <input type="submit"  values="提交" />
  <span>` error_message `</span>
  </p>
  </form>
  </body>
  </html>
  2)在app文件views.py文件中修改为:
  from django.shortcuts import render
  from django.shortcuts import redirect
  def login(request):
  error_message=""
  if request.method == "POST":
  user = request.POST.get('user',None)
  pwd = request.POST.get('pwd', None)
  print(user,pwd)
  if user == 'root' and pwd == '123456':
  return redirect('http://www.baidu.com')
  else:
  error_message = "用户名或密码错误"
  return render(request, 'index.html',{'error_message':error_message})
  3) 当输入错误信息时,浏览器访问效果为:
DSC0005.png

  到此,能够实现用户名为root密码为123456的用户登录,并且跳转到百度首页。而且实现了当用户输入错误的用户名或密码时,提示“用户名或者密码错误”!
  下面将实现后台管理用户。
  8、首先在templates目录中创建一个名为home.html的HTML文件,文件内容如下:
  <!DOCTYPE html>
  <html lang="en">
  <head>
  <meta charset="UTF-8">
  <title>Title</title>
  </head>
  <body>
  <table>
  <tr>
  <td>张三</td>
  <td>1992</td>
  <td>女</td>
  </tr>
  <tr>
  <td>李四</td>
  <td>1993</td>
  <td>男</td>
  </tr>
  <tr>
  <td>王五</td>
  <td>1997</td>
  <td>男</td>
  </tr>
  </table>
  </body>
  <html>
  9、在APP文件cmdb中的views.py中定义home函数,并把redirect中的地址改为/home
  from django.shortcuts import render
  from django.shortcuts import redirect
  def login(request):
  error_message=""
  if request.method == "POST":
  user = request.POST.get('user',None)
  pwd = request.POST.get('pwd', None)
  print(user,pwd)
  if user == 'root' and pwd == '123456':
  return redirect('/home')
  else:
  error_message = "用户名或密码错误"
  return render(request, 'index.html',{'error_message':error_message})
  def home(request):
  return render(request,'home.html')
  10、在项目文件test01的urls.py中加入映射关系from django.conf.urls import url
  from django.contrib import admin
  from django.shortcuts import HttpResponse  #导入HttpServer模块
  import time                                #加入
  from cmdb import views                    #导入cmdb app中的views
  def home(request):                         #定义函数home
  return HttpResponse('<h1>这是我的第一个Django程序!!!<h1>')
  urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^index.html',home),           #添加index.html
  url(r'^login',views.login),   #将cmdb app添加到url中
  url(r'^home',views.home)
  ]
  11、浏览器测试
  1) 浏览器中输入用户登录地址:127.0.0.1:8000/login
DSC0006.png

  2) 输入正确的用户名和密码,正常跳转到127.0.0.1:8000/home页面
DSC0007.png

  到此,当用户输入正确的用户名和密码时,能够实现跳转,并且能够能够看到之前在home.html文件中输入的三位用户的信息,但是这些用户的信息无法灵活改变,已经在html文件中写死了。
  下面将进行将后台列表中的用户,用循环的方式,打印在前端页面上。
  12、首先需要在home.html文件中添加一个循环,添加后home.html文件如下:
<!DOCTYPE html>  <html lang="en">
  <head>
  <meta charset="UTF-8">
  <title>Title</title>
  </head>
  <body>
  <table>
  {% for row in user_list %}
  <tr>
  <td>` row`.`username `</td>
  <td>` row`.`gender `</td>
  <td>` row`.`email `</td>
  </tr>
  {% endfor    %}
  <tr>
  <td>李四</td>
  <td>1993</td>
  <td>男</td>
  </tr>
  <tr>
  <td>王五</td>
  <td>1997</td>
  <td>男</td>
  </tr>
  </table>
  </body>
  <html>
  【注意】:
  1) Django中在html文件中加入文件的方法:
  {% for row in user_list %}   #循环的开始,需要一对大括号,并且里面有两个%
  <tr>
  <td>` row`.`username `</td>
  <td>` row`.`gender `</td>
  <td>` row`.`email `</td>
  </tr>
  {% endfor    %}         #循环的结尾也得有一对大括号和两个%
  2) row表示一个字典
  3) 引入单变量值时需要两个大括号
  {% for row in user_list %}
  <tr>
  <td>` row`.`username `</td>
  <td>` row`.`gender `</td>
  <td>` row`.`email `</td>
  </tr>
  {% endfor    %}
  这里的username、gender和email与APP文件中views.py中的username、gender、email相对应。
  13、修改APP文件中的views.py文件,加入USER_LIST列表和一个循环,修改后的views.py文件如下:
from django.shortcuts import render  from django.shortcuts import redirect
  def login(request):
  error_message=""
  if request.method == "POST":
  user = request.POST.get('user',None)
  pwd = request.POST.get('pwd', None)
  print(user,pwd)
  if user == 'root' and pwd == '123456':
  return redirect('/home')
  else:
  error_message = "用户名或密码错误"
  return render(request, 'index.html',{'error_message':error_message})
  USER_LIST=[
  {'username':'qiuuuu','email':'abcdefg','gender':'male'}
  ]
  for index in range(20):
  temp = {'username':'qiuuuu'+str(index),'email':'abcdef','gender':'male'}
  USER_LIST.append(temp)
  #str(index)表示将index的值变为字符型,range(20)表示数字1到20之间的整数从小到大排列。
  def home(request):
  return render(request,'home.html',{'user_list':USER_LIST})
  14、在项目文件test01中的urls.py中加入对应关系,加入后的urls.py文件如下:
from django.conf.urls import url  from django.contrib import admin
  from django.shortcuts import HttpResponse  #导入HttpServer模块
  import time                                #加入
  from cmdb import views                    #导入cmdb app中的views
  def home(request):                         #定义函数home
  return HttpResponse('<h1>这是我的第一个Django程序!!!<h1>')
  urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^index.html',home),           #添加index.html
  url(r'^login',views.login),   #将cmdb app添加到url中
  url(r'^home',views.home),
  ]
  15、浏览器输入127.0.0.1:8000/login,然后输入正确的用户名和密码后跳转到home.html页面的效果为:
DSC0008.png

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-549201-1-1.html 上篇帖子: python学习笔记文件操作(六) 下篇帖子: python: 字典嵌套
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表