目录
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 %}
--这样在提交数据的时候就不会直接报错了...