django视图

写一个登陆页面,更好的理解django工作流程

  1. 先写一个登陆页面,在templates添加index.html
    <html>
    <head>
    <title>Django Page</title>
    </head>
    <body>
    <h1>发布会管理</h1>
    <form method="post" action="/login_action/">
    <input name="username" type="text" placeholder="username" ><br>
    <input name="password" type="password" placeholder="password"><br>
    {{error}}<br>
    <button id="btn" type="submit">登录</button>
    {% csrf_token %}
    </form>
    </body>
    </html>
  2. 再去views添加index函数
    from django.shortcuts import render
    def Index(request):
      return render(request,"index.html")
  3. 再去urls添加路由
    path("dl",views.Index)
  4. 输入网址,就能看到登陆页面了
    http://127.0.0.1:8000/dl

get和post请求

 

  • get和post请求

    get:从指定资源请求数据
    post:向指定资源请求要处理的数据

  • 添加get/post请求

    给form添加method属性
    method="get"/"post"

  • get请求

    会将请求的数据添加到url中,
    路径后面跟问号“?”,username 和 password 为 
    HTML 代码中<input>标签的 name 属性值,username=admin 表示用户名输入框得到的输入数据为“admin”。 
    password=admin123 密码输入框得到的输入数据为“admin123”。多个参数之间用“&”符号隔开。

  • post请求

    post请求比较安全,为防止跨站请求伪造,要在form中添加CSRF 令牌。在 from 表单中添加{% csrf_token %}。
    <form method="post" action="/login_action/">
    <input name="username" type="text" placeholder="username" ><br>
    <input name="password" type="password" placeholder="password"><br>
    {{error}}<br>
    <button id="btn" type="submit">登录</button>
    {% csrf_token %}
    </form>
    发送请求后,F12查看请求数据,当页面向 Django 服务器发送一个 POST 请求时,服务器端要求客户 
    端加上 csrfmiddlewaretoken 字段,该字段的值为当前会话 ID 加上一个密钥的散列值

处理登陆请求

  现在了解了将表单中的数据提交给服务器的方式(GET/POST),那么将登录数据提交给 Django 服务器 

  的谁来处理?可以通过 form 表单的 action 属性来指定提交的路径
  • form添加action属性

    <form method="post" action="/login_action/">

  • urls添加/login_action/路由

    path('login_action/', views.login_action)

  • views添加login_action函数

    def login_action(request):
      if request.method=='POST':
           username=request.POST.get("username","")   
               password=request.POST.get("password","")  #通过 request.POST 来获取 POST 请求。通过.get()方法来寻找 name 为“username”和“password” 的 POST 参数,如果参数没有提交,返回一个空的字符串。此处                   #“username”和“password”对应 form 表 单中<input> 标签的 name 属性,可见这个属性的重要性。
               if username=="admin" and password=='123456':
                   response=HttpResponseRedirect("/event_manage/")#重定向到登陆成功的页面
                   response.set_cookie("use",username,3600) #添加cookie
                   return response. #返回响应数据
              else:
                   return render(request,'index.html',{"error":"username or password error"}). #否则,将通过 render 返回 index.html 登录页面,并且顺带返回 错误提示的字典“{'error': 'username or password error!'}”
                  #需要在index.html页面添加{{ error }},它对应 render 返回字典中的 key,并且在登录失败 的页面中显示 value,即“username or password error
           else:

                   return render(request,'index.html',{"error":"username or password error"})
  • 因为在登陆成功时添加了重定向的页面,所以要增加登陆成功页面

    <html>
    <head>
    <title>Event Manage Page</title>
    </head>
    <body>
    <h1>Login Success!</h1>
    <div style="float:right;">
    <a>嘿!{{ user }} 欢迎</a><hr/>
    </div>    #修改.../templates/event_manage.html 页面,添加<div>标签来显示用户登录的用户名。
    </body>
    </html>
  • 在urls添加路由

    path('event_manage/',views.event_manage)
  • 在views添加函数

    def event_manage(request):
    username=request.COOKIES.get("user",'')#读取浏览器cookie
    return render(request,"event_manage.html",{"user":username})

cookie

  • cookie(相当于存折,所有信息都在存折上)

    正统的 Cookie 分发是通过扩展 HTTP 协议来实现的,服务器通过在 HTTP 的响应头中加上 
    一行特殊的指示以提示浏览器按照指示生成相应的 Cookie。

  • 添加cookie

    登陆中添加cookie
    response.set_cookie("user",username,3600) #添加cookie

    #这里给 set_cookie()方法传了三个参数,第一个参数“user”是用于表示写入浏览器的 Cookie 名,第二个 
    参数 username 是由用户在登录页上输入的用户名,第三个参数 3600 用于表示该 cookie 信息在浏览器中的停 
    留时间,默认以秒为单位。

    登陆成功页面读取cookie
    username=request.COOKIES.get("user",'')#读取浏览器cookie

    #在 event_manage 视图函数中,通过 request.COOKIES 来读取 Cookie 名为“user”的值。并且通过 render 
    将和 event_manage.html 页面一起返回给客户端浏览器。

session

  • 添加session(相当于银行卡,信息都在取款机里)

    登陆中添加session
    request.session['user'] = username # 将 session 信息记录到浏览器

    登陆成功页面读取cookie
    username = request.session.get('user', '') # 读取浏览器 session
  • 保存session
    这时在登陆账号会报错:“no such table: django_session”,因为服务器没有保存session的地方
    这时需要数据迁移,通过“migrate”命令进行数据迁移。(因为Django 已经默认帮我设置 sqlite3 数据库
    >python3 manage.py migrate
    迁移成功后再次登陆就能正常登陆了
 

登陆admin后台

  • 登陆admin后台
    127.0.0.1:8000/admin/login/?next=/admin/

  • 创建账号
    目录下使用命令
    >python3 manage.py createsuperuser
    按提示创建账号

引用django认证登陆

  • Django 已经帮我们做好用户体系,那么就直接拿来使用好了。 打开.../sign/views.py 文件修改 login_action 函数
    from django.contrib import auth 
    def login_action(request):
          if request.method="POST":
                 username=request.POST.get('username',' ')
                 password=request.POST.get("password",'')
                 user=auth.auchenticate(username=username,password=password)
                 if user is not None:
                           auth.login(request,user) #登陆
                           request.session['user']=username #设置session
                           response=HttpResponseRedirect('/event_manage/')
                           return response
                 else:
                           return render(request,"index.html",{'error':"username or password error!'})

页面限制访问

  • 未加限制,只要地址正确就能登陆上,加装饰器限制后,只能登陆后跳转页面
    from django.contrib.auth.decorators import login_required
    @login_required
    def event_manage(request):
    username=request.session.get("user",'')#读取浏览器cookie
    return render(request,"event_manage.html",{"user":username})
 
 
 
 

 







        

  
    

 

 

 

 

 
  
 

 

posted on 2021-10-21 10:31  zfj822  阅读(27)  评论(0编辑  收藏  举报