zoukankan      html  css  js  c++  java
  • django之表单类

    一:表单类

    一般我们在html中自己写的表单类似于下面的样子

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>表单</title>
    </head>
    <body>
        <form action="www.xxx.com" method="POST">
    
            username:<input type="text" placeholder="username" name="username">
            passowrd:<input type="password" placeholder="password" name="password">
            submit:<input type="submit">
    
        </form>
    </body>
    </html>

    # 取值也是 request.POST.get("username") request.POST.get("password")

       表单类

    from django import forms
    
    class Login_Form(forms.Form):
        username = forms.CharField(label="你的名字",max_length=20)
        password = forms.CharField(label="你的密码",max_length=20)

       前端代码

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
       # 这里可以action="",因为get和post都走的是login这个视图。
        <form action="user/login/" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Submit" />
    </form>
    </body>
    </html>

      视图函数

    from django.http import HttpResponse
    from django.http import JsonResponse
    from django.shortcuts import render
    from .form_test import Login_Form
    
    def form_test_view(request):
       # 如果是post请求,将数据绑定到表单,直接存储在request.POST中,取值普通表单一样。
    if request.method == "POST": form = Login_Form(request.POST) if form.is_valid(): # 检验数据的有效性
           # 验证过的数据可以通过 form.cleaned_data取得,格式是一个字典
           print(form.cleaned_data)
           
    return HttpResponse("谢谢提交") else:
    # 如果是get请求,创建表单实例,将表单中的字段,传递到login.html中,进行渲染,渲染成input文本输入框。 form
    = Login_Form() return render(request,"login.html",{"form":form})

    from django.conf.urls import url
    from .views import index
    from .views import form_test_view
    urlpatterns = [
    url(r"^index/",index),
    url(r"^login",form_test_view)

    ]

     

    二:csrf 跨站伪造攻击

  • 相关阅读:
    日记搬迁
    学生会管理系统(JavaWeb与数据库课程小实践)
    疯狂忙碌边缘
    英语复习二:每单元的翻译篇章
    Don't always upset yourself !
    一文教你读懂并使用GTD高效时间管理法
    Day05-黑马学习篇(二)matplot基本绘图函数集合
    Day04-黑马学习篇(一)matplot画图基本要点
    Day03-基础篇(四)Pandas与数据清洗
    Day02 基础篇(三)用NumPy快速处理数据
  • 原文地址:https://www.cnblogs.com/meloncodezhang/p/11789709.html
Copyright © 2011-2022 走看看