zoukankan      html  css  js  c++  java
  • django框架中的form组件的用法

    form组件的使用

    先导入:

    from django.forms import Form
    from django.forms import fields
    from django.forms import widgets
    from django.core.validators import RegexValidator
    from django.core.exceptions import ValidationError

    在创建类,继承Form(定义input框的验证规则)

    class Loginform(Form):
        username=fields.CharField(error_messages={"required":"用户名不能为空"},
        widget=widgets.TextInput(attrs={"class":"form-control"}))
        password=fields.CharField(error_messages={"required":"密码不能为空"},
        widget=widgets.PasswordInput(attrs={"class":"form-control"}))
    
        def clean_username(self):
            # ...
            user = self.cleaned_data['username']
            is_exsit = models.Userinfo.objects.filter(username=user).count()
            if not is_exsit:
                raise ValidationError('用户名不存在')
            return user

    在实例化创建对象,将对象返回给render函数进行渲染

       if request.method=="GET":
            form=Loginform()
            return render(request,"login.html",{"form":form})

    模板渲染

    用户名:{{ form.username }}{{ form.errors.username.0 }}
    密码:{{ form.password}}{{ form.errors.password.0 }}

    用户输入信息提交后进行验证

     form=Loginform(data=request.POST)
        if form.is_valid(): #是否验证成功
            user=models.Userinfo.objects.filter(**form.cleaned_data).first() #通过验证则进行数据库比对
            if user:
                request.session[settings.WXP]={"name":user.username}
                return redirect("/index/")
            form.add_error('password', ValidationError('用户名或密码错误'))
            return render(request,"login.html",{"form":form})
        else:
            return render(request,"login.html",{"form":form}) #没通过验证则返回错误信息

    解决数据源无法实时更新的方法

    重写__init__方法(推荐使用)
    class ClassForm(Form):
        caption = fields.CharField(error_messages={'required':'班级名称不能为空'})            
        headmaster_id = fields.ChoiceField(choices=[])
        def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.fields['headmaster_id'].choices = models.UserInfo.objects.filter(ut_id=2).values_list('id','username')
    方法一
    #使用ModelChoiceField创建字段
    from django.forms.models import ModelChoiceField
    class ClassForm(Form):
        caption = fields.CharField(error_messages={'required':'班级名称不能为空'})        
        headmaster_id = ModelChoiceField(queryset=models.UserInfo.objects.filter(ut_id=2))
    方法二
  • 相关阅读:
    Git 简要教程
    SDK更新失败问题解决
    常用安卓操作
    MongoDB本地安装与启用(windows 7/10)
    windows 快捷键收集
    windows 常用命令
    Lambda Expression Introduction
    对 load_breast_cancer 进行 SVM 分类
    Support Vector Machine
    使用 ID3 对 Titanic 进行决策树分类
  • 原文地址:https://www.cnblogs.com/wxp5257/p/7794094.html
Copyright © 2011-2022 走看看