zoukankan      html  css  js  c++  java
  • Django 之Form表单的常用操作

    Django是一个开放源代码的Web应用框架,由Python写成。采用了MTV的框架模式,即模型M,视图V和模版T。它最初是被开发来用于管理劳伦斯出版集团旗下的一些以新闻内容为主的网站的,即是CMS(内容管理系统)软件。并于2005年7月在BSD许可证下发布。这套框架是以比利时的吉普赛爵士吉他手Django Reinhardt来命名的。 -- 百度百科

    普通Form表单的提交

    <!-- name:index.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form action="/" method="post">
            <p>账号:<input type="text" name="username"><span>{{ error.username }}</span></p>
            <p>密码:<input type="password" name="password"><span>{{ error.password }}</span></p>
            <input type="submit" value="提交请求">
        </form>
    </body>
    </html>
    
    # name: views.py
    from django.shortcuts import render,HttpResponse
    
    def index(request):
        if request.method == "GET":
            return render(request,"index.html")
        else:
            username = request.POST.get("username")
            password = request.POST.get("password")
            error = {"username":"","password":""}
            if len(username) > 10:
                error["username"]="用户名不能大于10"
            if len(password) < 5:
                error["password"] = "密码不能小于5"
            return render(request,"index.html",{"error":error})
    

    Form实现登录表单

    <!--name:index.html-->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form action="/" method="post" novalidate>
            <p>账号: {{ form.username }} {{ form.username.errors.0 }}</p>
            <p>密码: {{ form.password }} {{ form.errors.password }}</p>
            <p>重复: {{ form.RepeatPass }} {{ form.errors.RepeatPass }}</p>
            <input type="submit" value="提交">
        </form>
    </body>
    </html>
    
    # name:views.py
    from django.shortcuts import render,HttpResponse
    from django.forms import Form,fields,widgets
    from django.core.exceptions import ValidationError
    
    class LoginForm(Form):
        username = fields.CharField(
            required = True,
            max_length = 10,
            error_messages={"required":"该字段不能为空"},
            widget=widgets.TextInput(attrs={"placeholder":"请输入用户名","class":"form-control"})
        )
        password = fields.CharField(
            required = True,
            max_length=10,
            error_messages={"required":"密码字段不能为空","min_length":"密码最小长度为5"},
            widget=widgets.PasswordInput(attrs={"placeholder":"请输入密码","class":"form-control"})
        )
        RepeatPass = fields.CharField(
            required=True,
            max_length=10,
            error_messages={"required":"密码字段不能为空","min_length":"密码最小长度为5"},
            widget=widgets.PasswordInput(attrs={"placeholder":"重复输入密码","class":"form-control"})
        )
    
        # 自定义方法(局部钩子)密码必须包含字母和数字
        def clean_password(self):
            if self.cleaned_data.get("password").isdigit() or self.cleaned_data.get("password").isalpha():
                raise ValidationError("密码必须包含数字和字母")
            else:
                return self.cleaned_data["password"]
        # 自定义方法(全局钩子, 检验两个字段),检验两次密码是否一致
        def clean_RepeatPass(self):
            if self.cleaned_data.get("password") != self.cleaned_data.get("RepeatPass"):
                raise ValidationError("两次输入密码不正确")
            else:
                return self.cleaned_data
    
    def index(request):
        if request.method =="GET":
            form = LoginForm()
            return render(request, "index.html", {"form": form})
        else:
            form = LoginForm(request.POST)
            if form.is_valid():
                # username = form.data['username']
                data = form.cleaned_data
                username = data.get("username")
                password = data.get("password")
                print(username,password)
                return render(request, "index.html", {"form": form})
        return render(request, "index.html", {"form": form})
    

    其他常用Form表单

    <!--name: index.html-->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form action="/" method="post">
            {% for field in form %}
                <p>{{ field.label_tag }} {{ field }} {{ field.errors.0 }}</p>
            {% endfor %}
            <input type="submit" value="提交" />
        </form>
    </body>
    </html>
    
    # name: views.py
    from django.shortcuts import render,HttpResponse
    from django.forms import Form,fields,widgets
    
    class MyForm(Form):
        hobby = fields.ChoiceField(
            label="单选框:",
            required=True,
            initial=1,                # 默认选择1号
            choices=( (1,"篮球"),(2,"足球"),(3,"乒乓球"),(4,"滚球")),
            widget=widgets.RadioSelect()
        )
        select = fields.ChoiceField(
            label="单选框(默认):",
            required=True,
            initial=1,
            choices=( (1,"篮球"),(2,"足球"),(3,"乒乓球"),(4,"滚球")),
            widget=widgets.Select()
        )
        multiple = fields.MultipleChoiceField(
            label="复选框",
            choices=((1, "篮球"), (2, "足球"), (3, "羽毛球"), (4, "排球")),
            initial=[2, 4],
            widget=widgets.SelectMultiple()
        )
        checkbox = fields.ChoiceField(
            label="单项复选框",
            initial="checked",  # 默认为勾选
            widget=widgets.CheckboxInput()
        )
        multselect = fields.MultipleChoiceField(
            label="多项复选框",
            choices=((1, "篮球"), (2, "足球"), (3, "羽毛球"), (4, "排球")),
            initial=[1, 3],
            widget=widgets.CheckboxSelectMultiple()
        )
        data = fields.DateField(
            label="选择日期",
            widget = widgets.DateInput(attrs={"type":"date"})
        )
    def index(request):
        if request.method=="GET":
            form = MyForm()
            return render(request,"index.html",{"form":form})
        else:
            form = MyForm(request.POST)
            if form.is_valid():
                data = form.cleaned_data
                print(data.get("hobby"))
        return HttpResponse("hello lyshark")
    

    Form实现用户注册

    <!--name: index.html-->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <div>
            <form action="/" method="post">
                <p>{{ form.username.label }} {{ form.username }}</p>
                <p>{{ form.password.label }} {{ form.password }}</p>
                <p>{{ form.mobile.label }} {{ form.mobile }} </p>
                <p>{{ form.email.label }} {{ form.email }} </p>
                <p>{{ form.text }} </p>
                <p><input type="submit" value="提交请求"></p>
            </form>
        </div>
    </body>
    </html>
    
    # name: models.py
    from django.db import models
    
    class User(models.Model):
        id = models.AutoField(primary_key=True)
        username = models.CharField(max_length=64)
        password = models.CharField(max_length=32)
        mobile = models.CharField(max_length=32)
        email = models.EmailField(max_length=64)
        text = models.CharField(max_length=128)
    
    # name: views.py
    from django.shortcuts import render,HttpResponse
    from MyWeb import models
    from django.forms import Form,fields,widgets
    from django.core.validators import RegexValidator
    from django.core.exceptions import ValidationError
    
    class UserForm(Form):
        username = fields.CharField(
            label = "账号: ",          # 给表单加一个标签
            required = True,           # 不允许字段为空值
            min_length=4,              # 设置最小长度
            max_length = 10,           # 设置最大长度
            validators=[ RegexValidator(r'^[0-9a-zA-Z]+$',"用户账号只能使用,0-9a-z") ],
            error_messages={"required":"该字段不能为空","invalid":"无效的用户名",
                            "min_length":"最小长度为5","max_length":"最大长度为10"},
            widget=widgets.TextInput(attrs={"placeholder":"请输入用户名","class":"form-control"})
        )
        password = fields.CharField(
            label = "密码: ",
            required = True,
            min_length=5,
            max_length=10,
            error_messages={"required":"密码字段不能为空","min_length":"密码最小长度为5"},
            widget=widgets.PasswordInput(attrs={"placeholder":"请输入密码","class":"form-control"})
        )
        mobile = fields.CharField(
            label = "手机: ",
            required=True,
            validators=[RegexValidator('[0-9]', "手机号必须是数字")],
            error_messages={"required":"该字段不能为空"},
            widget=widgets.TextInput(attrs={"placeholder": "手机号","class": "form-control"})
        )
        email = fields.EmailField(
            label="邮箱: ",
            required=True,
            error_messages={"required":"邮箱不能为空!!","invalid":"无效的邮箱"},
            widget=widgets.EmailInput(attrs={"placeholder": "邮箱", "class": "form-control"})
        )
        text = fields.CharField(
            required=True,
            widget=widgets.Textarea(attrs={"placeholder": "畅言,欢迎留言...", "class": "form-control",
                                           "style":"margin: 0px;  203px; height: 98px;"})
        )
    
    def index(request):
        if request.method =="GET":
            form = UserForm()
            return render(request, "index.html", {"form": form})
        else:
            form = UserForm(request.POST)
            if form.is_valid():
                # username = form.data['username']
                data = form.cleaned_data
                username = data.get("username")
    
                is_exits = models.User.objects.filter(username="admin").count()
                if is_exits != 0:
                    return HttpResponse("您注册的用户已存在")
                else:
                    models.User.objects.create(**data)
                    return HttpResponse("恭喜您的账号注册完成了")
            else:
                return render(request, "index.html", {"form": form.errors})
        return render(request, "index.html", {"form": form})
    

    实现用户验证

    index.html

    <head>
        <meta charset="UTF-8">
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    </head>
    <body>
    
    <form action="/" method="post">
        <p> {{ form.email }}</p>
        <p> {{ form.code }} <a id="fetch_code" class="fetch-code" href="javascript:void(0);">获取验证码</a></p>
        <input type="submit" value="提交">
    </form>
    
    
    <script type="text/javascript">
        $("#fetch_code").click(function(){
            var email = $("#email").val();        // 获取到用户邮箱
            if(email.trim().length != 0)
            {
                $("#fetch_code").empty();
                $("#fetch_code").text("发送成功");
                $.ajax({
                    url:"/send_msg/",
                    type:"POST",
                    data:{email:email},
                    dataType:"json",
                    success:function(recv){
                    }
                })
            }
        })
    
    </script>
    

    models.py

    from django.db import models
    
    class SendMsg(models.Model):
        id = models.AutoField(primary_key=True)
        code = models.CharField(max_length=6)
        email = models.CharField(max_length=32, db_index=True)
        count = models.IntegerField(default=0)
        times = models.IntegerField(default=0)
    
    class UserInfo(models.Model):
        id = models.AutoField(primary_key=True)
        username = models.CharField(max_length=32, unique=True)
        password = models.CharField(max_length=32)
        email = models.CharField(max_length=32, unique=True)
    

    views.py

    from django.shortcuts import render,HttpResponse
    from django.core.mail import send_mail, send_mass_mail, EmailMultiAlternatives
    import re,time,random
    from MyWeb import models
    
    def SendMail(rand,user):
        title = "本次注册验证码是: {} 十分钟以内有效.".format(rand)
        ret = send_mail("Django 邮件通知",title,"smtpwho@163.com",[user])
        if ret:
            return 1
        return 0
    def send_msg(request):
        if request.method=="POST":
            email = request.POST.get("email")
            ret = re.match(r'^[0-9a-zA-Z\_-]+(.[0-9a-zA-Z\_-]+)*@[0-9a-zA-Z]+(.[0-9a-zA-Z]+){1,}$', email)
            if ret == None:
                print("不合法")
            else:
                ret = models.UserInfo.objects.filter(email=email).count()
                if ret == 1:
                    print("你的邮箱已经注册了,请换一个..")
                else:
                    ret = models.SendMsg.objects.filter(email=email).count()    # 查询出如果存在sendmsg表里,则不能让其注册
                    if ret !=0:
                        print("等待超时,暂时不嫩注册..")
                        times = int(time.time())
                        if times >=models.SendMsg.objects.filter(email=email).values("times"):
                            print(times)
                        else:
                            print("时间还没到")
    
                    else:
                        rand = random.randint(10000,20000)
                        if SendMail(rand,email):
                            times = int(time.time()+60)  # 一分钟只能注册一次
                            models.SendMsg.objects.create(email=email,code=rand,times=times)
        return render(request,"reg.html")
    
    def reg(request):
        if request.method == "POST":
            email = request.POST.get("email")
            code = request.POST.get("code")
            ret = models.SendMsg.objects.filter(email=email).values("email","code")[0]
            if ret['email']==email and ret['code']==code:
                print("正确了")
                username = request.POST.get("username")
                password = request.POST.get("password")
                ret = models.UserInfo.objects.filter(username=username).count()
                if ret == 0:
                    # 等于0说明没有这个用户,可以注册
                    models.UserInfo.objects.create(username=username,password=password,email=email)
                    print("注册完成了")
                else:
                    print("这个账号重复了,请换一个...")
            else:
                print("验证码错误")
        return render(request, "reg.html")
    

    urls.py

    from django.contrib import admin
    from django.urls import path
    from MyWeb import views
    urlpatterns = [
        path('admin/', admin.site.urls),
        path("reg/",views.reg),
        path("send_msg/",views.send_msg)
    ]
    
    

    settings.py

    STATIC_URL = '/static/'
    EMAIL_USER_TLS = True
    EMAIL_PORT = 25
    EMAIL_HOST = "smtp.163.com"
    EMAIL_HOST_USER = "smtpwho@163.com"
    EMAIL_HOST_PASSWORD = "123456789"
    

    版权声明: 本博客,文章与代码均为学习时整理的笔记,博客中除去明确标注有参考文献的文章,其他文章【均为原创】作品,转载请务必【添加出处】,您添加出处是我创作的动力!

    警告:如果您恶意转载本人文章,则您的整站文章,将会变为我的原创作品,请相互尊重!
  • 相关阅读:
    OCP 062【中文】考试题库(cuug内部资料)第29题
    413. 等差数列划分 力扣(中等) 找规律,细节
    264. 丑数 II 力扣(中等) 动态规划,不会
    313. 超级丑数 力扣(中等) 动态规划,不会做
    5840. 使字符串平衡的最小交换次数 力扣(中等) 第255场oppo周赛 猜出来的
    手写一个仿微信登录的Nodejs程序
    你不知道的CSS国际化
    React实现类似淘宝tab居中切换效果
    原来 CSS 这样写是会让 App 崩溃的
    css中class和id之间有什么区别?
  • 原文地址:https://www.cnblogs.com/LyShark/p/12098609.html
Copyright © 2011-2022 走看看