Python - Django - form 组件校验功能

app01/models.py:

from django.db import models


class UserInfo(models.Model):
    username = models.CharField(max_length=16)
    password = models.CharField(max_length=16)

创建一个 UserInfo 表

 

reg2.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册页面</title>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <form action="/reg2/" method="post" novalidate>
                {% csrf_token %}
                <div class="form-group {% if form_obj.username.errors.0 %}has-error{% endif %}">
                    {{ form_obj.username.label }}
                    {{ form_obj.username }}
                    <span class="help-block">{{ form_obj.username.errors.0 }}</span>
                </div>
                <div class="form-group {% if form_obj.password.errors.0 %}has-error{% endif %}">
                    {{ form_obj.password.label }}
                    {{ form_obj.password }}
                    <span class="help-block">{{ form_obj.password.errors.0 }}</span>
                </div>
                <p><input type="submit" class="btn btn-default"></p>
            </form>
        </div>
    </div>
</div>

</body>
</html>

views.py:

from django.shortcuts import render, HttpResponse
from app01 import models

from django import forms
from django.forms import widgets


class RegForm(forms.Form):
    username = forms.CharField(
        min_length=5,
        label="用户名",
        error_messages={
            "min_length": "用户名不能小于5位!",
        },
        widget=widgets.TextInput(attrs={"class": "form-control"})
    )

    password = forms.CharField(
        min_length=6,
        label="密码",
        error_messages={
            "min_length": "密码不能少于6位!",
        },
        widget=widgets.PasswordInput(attrs={"class": "form-control"}, render_value=True)
    )


def reg2(request):
    form_obj = RegForm()  # GET 请求

    if request.method == "POST":
        form_obj = RegForm(request.POST)
        # 让 form 来帮我们进行校验
        if form_obj.is_valid():
            # 如果通过校验
            # 所有经过校验的数据都保存在 form_obj.cleaned_data
            print(form_obj.cleaned_data)
            # 把数据存到数据库中,因为 form_obj.cleaned_data 是字典,所以用 ** 进行拆分
            models.UserInfo.objects.create(**form_obj.cleaned_data)
            return HttpResponse("注册成功")

    return render(request, "reg2.html", {"form_obj": form_obj})

访问,http://127.0.0.1:8000/reg2/

 

点击 “提交”

 

 再看一下数据库

 

posted @ 2019-09-07 15:16  Sch01aR#  阅读(266)  评论(0编辑  收藏  举报