python框架-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>

    <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)

]

 python框架-django中的表单类

python框架-django中的表单类

二:csrf 跨站伪造攻击

相关推荐