3-Django项目继续--初识ModelForm

目录

ModelForm

认识ModelForm

优势

初识Form

初识ModelForm

添加信息

views.py

add_student_new.html

修改信息

views.py

views.py

add_student_new.html


ModelForm

认识ModelForm

  • 优势

    • 1、方便校验用户提交的数据

    • 2、页面展示错误提示

    • 3、数据库字段很多的情况下,每个字段无需手写.

    • 4、关联数据,无需手动获取.

  • 初识Form

    from django import forms
    class Add_Student(forms.Form):
        user = forms.CharField(widget=forms.TextInput)
        pwd = forms.CharField(widget=forms.PasswordInput)
    ​
    def add_student_form(request):
        form = Add_Student()
        return render(request, "stu_data/add_stu_new.html",{"form":form})

  • 初识ModelForm

  • from django import forms
    ​
    class Add_Student(forms.ModelForm):
        class Meta:
            model = models.Student
            # 获取数据表当中的字段
            # fields = ["name", "age", "gender"]
            # 获取全部字段
            fields = "__all__"
            # 给字段单独添加属性
            # widgets = {
            #     "name": forms.TextInput(attrs={"class":"form-control"}),
            #     "age": forms.TextInput(attrs={"class":"form-control"}),
            #     "gender": forms.TextInput(attrs={"class":"form-control"})
            # }

添加信息

  • views.py

    class Add_Student(forms.ModelForm):
        class Meta:
            model = models.Student
            # 获取数据表当中的字段
            # fields = ["name", "age", "gender"]
            # 获取全部字段
            fields = "__all__"
            # 给字段单独添加属性
            # widgets = {
            #     "name": forms.TextInput(attrs={"class":"form-control"}),
            #     "age": forms.TextInput(attrs={"class":"form-control"}),
            #     "gender": forms.TextInput(attrs={"class":"form-control"})
            # }
    ​
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # name是输入框上面的名字
            # field 是输入框
            for name, field in self.fields.items():
                field.widget.attrs = {"class": "form-control", "autocomplete": "off"}
    ​
    ​
    def add_student_form(request):
        if request.method == "GET":
            form = Add_Student()
            # print(form)
            return render(request, "stu_data/add_stu_new.html", {"form": form})
    ​
        # 获取post请求提交的数据
        form = Add_Student(data=request.POST)
        # 校验数据的完整性
        if form.is_valid():
            # 保存到数据表
            form.save()
            return redirect("/class/data/")
        return render(request, "stu_data/add_stu_new.html", {"form": form})
  • add_student_new.html

    {% extends "index/index.html" %}
    {% load static %}
    ​
    {% block content %}
        <div class="container">
            <div class="panel panel-success">
                <div class="panel-heading">
                    <h3 class="panel-title">添加信息</h3>
                </div>
                <div class="panel-body">
                    <div class="form-group">
                        <form method="post" novalidate>
                            {% csrf_token %}
                            {% for item in form %}
                                <label for="exampleInputEmail1" class="col-sm-2" >{{ item.label }}</label>
                                {{ item }}
                                <span style="color: red">{{ item.errors.0 }}</span>
                            {% endfor %}
                            <button type="submit" class="btn btn-success">提交</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    ​
    {% endblock %}
    ​
    {% block js %}
    {#    <script src="{% static 'js/layui.js' %}"></script>#}
    {#    <script>#}
    {#        layui.use(function () {#}
    {#            var laydate = layui.laydate;#}
    {#            // 渲染#}
    {#            laydate.render({#}
    {#                elem: '#id_class_time'#}
    {#            });#}
    {#        });#}
    {#    </script>#}
    {% endblock %}

修改信息

  • views.py

    def modify_student(request, nid):
        title = "修改信息"
        obj = models.Student.objects.filter(id=nid).first()
        if request.method == "GET":
            form = Add_Student(instance=obj)
            return render(request, "stu_data/add_stu_new.html", {"form": form,"title":title})
    ​
        form = Add_Student(data=request.POST, instance=obj)
        if form.is_valid():
            form.save()
            return redirect("/class/data/")
        return render(request, "stu_data/add_stu_new.html", {"form": form, "title": title})

views.py

from django.shortcuts import render, redirect
from demo_one import models

.
.
.


from django import forms


class Add_Student(forms.ModelForm):
    class Meta:
        model = models.Student
        # 获取数据表当中的字段
        # fields = ["name", "age", "gender"]
        # 获取全部字段
        fields = "__all__"
        # 给字段单独添加属性
        # widgets = {
        #     "name": forms.TextInput(attrs={"class":"form-control"}),
        #     "age": forms.TextInput(attrs={"class":"form-control"}),
        #     "gender": forms.TextInput(attrs={"class":"form-control"})
        # }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # name是输入框上面的名字
        # field 是输入框
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "autocomplete": "off"}


def add_student_form(request):
    title = "添加信息"
    if request.method == "GET":
        form = Add_Student()
        # print(form)
        return render(request, "stu_data/add_stu_new.html", {"form": form,"title":title})

    # 获取post请求提交的数据
    form = Add_Student(data=request.POST)
    # 校验数据的完整性
    if form.is_valid():
        # 保存到数据表
        form.save()
        return redirect("/class/data/")
    return render(request, "stu_data/add_stu_new.html", {"form": form})


# class Modify_Student(forms.ModelForm):
#     class Meta:
#         model = models.Student
#         # 获取数据表当中的字段
#         fields = ["name"]
#         # 获取全部字段
#         # fields = "__all__"
#         # 给字段单独添加属性
#         # widgets = {
#         #     "name": forms.TextInput(attrs={"class":"form-control"}),
#         #     "age": forms.TextInput(attrs={"class":"form-control"}),
#         #     "gender": forms.TextInput(attrs={"class":"form-control"})
#         # }
#
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         # name是输入框上面的名字
#         # field 是输入框
#         for name, field in self.fields.items():
#             field.widget.attrs = {"class": "form-control", "autocomplete": "off"}

# 修改信息

def modify_student(request, nid):
    title = "修改信息"
    obj = models.Student.objects.filter(id=nid).first()
    if request.method == "GET":
        form = Add_Student(instance=obj)
        return render(request, "stu_data/add_stu_new.html", {"form": form,"title":title})

    form = Add_Student(data=request.POST, instance=obj)
    if form.is_valid():
        form.save()
        return redirect("/class/data/")
    return render(request, "stu_data/add_stu_new.html", {"form": form, "title": title})


add_student_new.html

{% extends "index/index.html" %}
{% load static %}

{% block content %}
    <div class="container">
        <div class="panel panel-success">
            <div class="panel-heading">
                <h3 class="panel-title">{{ title }}</h3>
            </div>
            <div class="panel-body">
                <div class="form-group">
                    <form method="post" novalidate>
                        {% csrf_token %}
                        {% for item in form %}
                            <label for="exampleInputEmail1" class="col-sm-2" >{{ item.label }}</label>
                            {{ item }}
                            <span style="color: red">{{ item.errors.0 }}</span>
                        {% endfor %}
                        <button type="submit" class="btn btn-success">提交</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

{% endblock %}

{% block js %}
{#    <script src="{% static 'js/layui.js' %}"></script>#}
{#    <script>#}
{#        layui.use(function () {#}
{#            var laydate = layui.laydate;#}
{#            // 渲染#}
{#            laydate.render({#}
{#                elem: '#id_class_time'#}
{#            });#}
{#        });#}
{#    </script>#}
{% endblock %}

--这样在提交数据的时候就不会直接报错了...

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

金灰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值