zoukankan      html  css  js  c++  java
  • (五)表单类的创建和使用

    一、创建表单

    表单类的作用:
    1、在template模板中,使用Django中已存在的表单,快速生成表单控件,该类表单控件已存在验证数据合法性的功能,开箱即用。
    2、在view视图函数中,使用表单类对Model模型对应的数据库表进行数据的存储作用

    表单类组件的类型:
    1、Form组件:

    • 生成页面可用的HTML标签
    • 对用户提交的数据进行校验
    • 保留上次输入的内容
    • 表单仅提供数据的读取使用
    • 可验证

    2、ModelForm组件:(Model和Form的结合)

    • 可验证,用户可对表单控件数据校验
    • 对数据库进行操作

    创建前需要在应用目录下新增from.py文件,文件用来存放该应用下需要创建的表单类

    二、 表单类的使用

    #登录的表单类(不会对数据操作)
    class LoginForm(forms.Form):
        username = forms.CharField()
        password = forms.CharField(widget=forms.PasswordInput)
    
    #注册的表单类(会对数据库操作)
    class RegistrationForm(forms.ModelForm):
        # password 和 password2新增的表单控件
        password = forms.CharField(label="密码",widget=forms.PasswordInput)
        password2 = forms.CharField(label="确认密码",widget=forms.PasswordInput)
        
       
        class Meta:
            model=User #表示表单类操作User模型
           fields=("username","email") #列出username、email字段,表单控件包含这两项
       # 验证
       def clean_password2(self):
           cd = self.cleaned_data
           if cd["password"] != cd["password2"]:
               raise forms.ValidationError("请再次确认密码")
           return cd["password2"]
    

    三、表单类在视图函数中的使用

    1、Form组件的控件使用

    使用在GET方法中,用于渲染出表单控件

    def user_login(request):
        if request.method == "GET":
            login_form = LoginForm()
            return render(request,"account/login.html",{"form":login_form})
    

    使用在POST方法中,用于验证

        login_form = LoginForm(request.POST)# request.POST获取用户填写的值
        if login_form.is_valid():
            user = authenticate(login_form.cleaned_data)
            if user:
                login(request,user)
                return HttpResponse("您已经登录成功....")
            else:
                return HttpResponse("您的用户名或密码错误,请重新登录")
        else:
            login_url = reverse("account:user_login")
            return redirect(login_url)
    

    2、ModelForm组件的控件使用

    使用在GET方法中,用于渲染出表单控件

    def user_Registration(request):
        if request.method == "GET":
            registration_form = RegistrationForm()
            return render(request,"account/register.html",{"form":user_form,"profile":phone_form})
    

    使用在POST方法中,用于对model模型对应的数据库表操作

    elif request.method == "POST":
        user_form = RegistrationForm(request.POST)
        userprofile_form = UserProfileForm(request.POST)
        if user_form.is_valid() and userprofile_form.is_valid():
            new_user = user_form.save(commit=False)
            new_user.set_password(user_form.cleaned_data['password2'])
            new_user.save()
            new_profile = userprofile_form.save(commit=False)
            new_profile.user = new_user  #这里保存对应user_id的外键
            new_profile.save()
            print("new_user",new_user)
            #新增UserInfo关联的用户
            UserInfo.objects.create(user=new_user)
    
            login_url = reverse("account:user_login")
            return redirect(login_url)
        else:
            return HttpResponse("注册失败")
    

    四、表单类在模板中的使用

    1、登录模板控件

    account/login.html

    {% block content %}
    <div class="container">
        <h1 class="mb-3 bd-text-purple-bright">登录</h1>
        <form class="js-validate" action="." method="post">
            {% csrf_token %}
            <div class="spadding">
                <label for="{{ form.username.id_for_label }}" class="title">用户名:</label>
                {{ form.username }}
            </div>
            <div class="spadding">
                <label for="{{ form.password.id_for_label }}" class="title">密码:</label>
                {{ form.password }}
            </div>
            <input type="submit" class="btn btn-block btn-primary" value="登录">
        </form>
    </div>
    {% endblock %}
    

    登录表单控件效果图:
    MHfbrT.md.png

    2、注册模板控件

    account/register.html

    {% block content %}
    <div class="container">
        <h1>注册</h1>
        <form class="form-horizontal" action="{% url 'account:register' %}" method="post">
            {% csrf_token %}
            <div class="form-group">
                <label for="{{ form.username.id_for_label }}" class="">用户名</label>
                <div id="{{ form.username.id_for_label }}" class="">{{ form.username }}</div>
                <label for="{{ form.email.id_for_label }}" class="">邮箱</label>
                <div id="{{ form.email.id_for_label }}" class="">{{ form.email }}</div>
                <label for="{{ form.password.id_for_label }}" class="">密码</label>
                <div id="{{ form.password.id_for_label }}" class="">{{ form.password }}</div>
                <label for="{{ form.password2.id_for_label }}" class="">确认密码</label>
                <div id="{{ form.password2.id_for_label }}" class="">{{ form.password2 }}</div>
            </div>
            <input type="submit" class="btn btn-primary btn-lg" value="注册">
        </form>
    </div>
    {% endblock %}
    

    注册表单控件效果图:
    MHhkZD.png

    五、表单类与数据库

    表单类对数据库的操作有两种:
    1、表单类无新增字段,操作数据库,对表单类绑定的数据,保存到数据库

    
    elif request.method == "POST":
        img = request.POST.get("img","")
        if img:
            userinfo = UserInfo.objects.get(user=request.user.id)
            userinfo.photo = img
            userinfo.save()
            return HttpResponse("1")
    
        else:
            print("上传文件,没有获取到任何内容~")
    

    2、表单类需新增字段,操作数据库,对表单类绑定的数据和新增的字段,保存到数据库

    user_form = RegistrationForm(request.POST)
    userprofile_form = UserProfileForm(request.POST)
    if user_form.is_valid() and userprofile_form.is_valid():
        new_user = user_form.save(commit=False) #不立即保存到数据库,需要新增表单类中未绑定的字段
        new_user.set_password(user_form.cleaned_data['password2'])
        new_user.save()
        new_profile = userprofile_form.save(commit=False)
        new_profile.user = new_user  #这里保存对应user_id的外键
        new_profile.save()
        print("new_user",new_user)
        #新增UserInfo关联的用户
        UserInfo.objects.create(user=new_user)
    
        login_url = reverse("account:user_login")
        return redirect(login_url)
    

    六、自定义表单类

    待写....

    总结:
    Django中自带的表单类,可以快速完成平常日常的控件开发工作,简化了开发功能,就像轮子一样,你可以学会直接用,你也可以去自己造。

  • 相关阅读:
    为什么hive表有数据,但count(*)返回0
    数仓建设时,要建历史表,用于保存历史数据,用于日后出问题时,起修复数据的作用。按日期分区,每天都把所有的数据存到当天的分区里
    get_json_object用以获取json类型的字段的值
    str_to_map语句,字符串类型变map类型
    按更新时间取最新记录
    hive临时表
    数仓分层
    次日留存、七日留存
    转义
    数据库三范式
  • 原文地址:https://www.cnblogs.com/yangsun/p/11915607.html
Copyright © 2011-2022 走看看