HTML頁面中利用form表單向後端提交數據時,都會寫一些獲取用戶輸入的標籤而且用form標籤把它們包起來。css
當須要對用戶的輸入作校驗,好比校驗用戶是否輸入,輸入的長度和格式等正不正確。若是用戶輸入的內容有錯誤就須要在頁面上相應的位置顯示對應的錯誤信息.。html
Django form組件就實現了上面所述的功能。前端
總結一下,其實form組件的主要功能以下:python
關於校驗:
1. 前端經過JS代碼作校驗 --> 最好有
2. 後端作校驗 --> 必需要有(由於前端的校驗能夠被跳過)jquery
一、from django import forms
二、定義一個form類git
class RegForm(forms.Form): user = forms.CharField() pwd = forms.CharField() email = forms.EmailField()
生成HTML:正則表達式
3. 實例化一個form對象, 傳遞到模板語言中數據庫
form_obj = RegFrom()
return render(request, "register.html", {"form_obj": form_obj})
4. 在目標語言中調用form對象的響應方法和屬性
三種方式:django
1. {{ form_obj.as_p }}
2. 單獨寫
{{ form_obj.pwd.label }}
{{ form_obj.pwd }}bootstrap
作校驗:
1. form_obj = RegForm(request.POST)
2. form_obj.is_valid()
內置的正則校驗器的使用
mobile = forms.CharField( label="手機", # 本身定製校驗規則 validators=[ RegexValidator(r'^[0-9]+$', '手機號必須是數字'), RegexValidator(r'^1[3-9][0-9]{9}$', '手機格式有誤') ], widget=widgets.TextInput(attrs={"class": "form-control"}), error_messages={ "required": "該字段不能爲空", } )
views.py
# 註冊 def register(request): error_msg = "" if request.method == "POST": username = request.POST.get("name") pwd = request.POST.get("pwd") # 對註冊信息作校驗 if len(username) < 6: # 用戶長度小於6位 error_msg = "用戶名長度不能小於6位" else: # 將用戶名和密碼存到數據庫 return HttpResponse("註冊成功") return render(request, "register.html", {"error_msg": error_msg})
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>註冊頁面</title> </head> <body> <form action="/reg/" method="post"> {% csrf_token %} <p> 用戶名: <input type="text" name="name"> </p> <p> 密碼: <input type="password" name="pwd"> </p> <p> <input type="submit" value="註冊"> <p style="color: red">{{ error_msg }}</p> </p> </form> </body> </html>
views.py
先定義好一個RegForm類:
from django import forms # 按照Django form組件的要求本身寫一個類 class RegForm(forms.Form): name = forms.CharField(label="用戶名") pwd = forms.CharField(label="密碼")
再寫一個視圖函數:
# 使用form組件實現註冊方式 def register2(request): form_obj = RegForm() if request.method == "POST": # 實例化form對象的時候,把post提交過來的數據直接傳進去 form_obj = RegForm(request.POST) # 調用form_obj校驗數據的方法 if form_obj.is_valid(): return HttpResponse("註冊成功") return render(request, "register2.html", {"form_obj": form_obj})
login2.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>註冊2</title> </head> <body> <form action="/reg2/" method="post" novalidate autocomplete="off"> {% csrf_token %} <div> <label for="{{ form_obj.name.id_for_label }}">{{ form_obj.name.label }}</label> {{ form_obj.name }} {{ form_obj.name.errors.0 }} </div> <div> <label for="{{ form_obj.pwd.id_for_label }}">{{ form_obj.pwd.label }}</label> {{ form_obj.pwd }} {{ form_obj.pwd.errors.0 }} </div> <div> <input type="submit" class="btn btn-success" value="註冊"> </div> </form> </body> </html>
建立Form類時,主要涉及到 【字段】 和 【插件】,字段用於對用戶請求數據的驗證,插件用於自動生成HTML;
各種標籤須要使用forms.widgets來生成,使用時導入便可
initial:初始值,input框裏面的初始值。
class LoginForm(forms.Form): username = forms.CharField( min_length=8, label="用戶名", initial="張三" # 設置默認值 ) pwd = forms.CharField(min_length=6, label="密碼")
error_messages:重寫錯誤信息。
class LoginForm(forms.Form): username = forms.CharField( min_length=8, label="用戶名", initial="張三", error_messages={ "required": "不能爲空", "invalid": "格式錯誤", "min_length": "用戶名最短8位" } ) pwd = forms.CharField(min_length=6, label="密碼")
password:
class LoginForm(forms.Form): ... pwd = forms.CharField( min_length=6, label="密碼", widget=forms.widgets.PasswordInput(attrs={'class': 'c1'}, render_value=True) )
radioSelect:單radio值爲字符串
class LoginForm(forms.Form): username = forms.CharField( min_length=8, label="用戶名", initial="張三", error_messages={ "required": "不能爲空", "invalid": "格式錯誤", "min_length": "用戶名最短8位" } ) pwd = forms.CharField(min_length=6, label="密碼") gender = forms.fields.ChoiceField( choices=((1, "男"), (2, "女"), (3, "保密")), label="性別", initial=3, widget=forms.widgets.RadioSelect() )
單選Select(initial)
class LoginForm(forms.Form): ... hobby = forms.fields.ChoiceField( choices=((1, "籃球"), (2, "足球"), (3, "雙色球"), ), label="愛好", initial=3, widget=forms.widgets.Select() )
多選Select(initial)
class LoginForm(forms.Form): ... hobby = forms.fields.MultipleChoiceField( choices=((1, "籃球"), (2, "足球"), (3, "雙色球"), ), label="愛好", initial=[1, 3], widget=forms.widgets.SelectMultiple() )
單選checkbox
class LoginForm(forms.Form): ... keep = forms.fields.ChoiceField( label="是否記住密碼", initial="checked", widget=forms.widgets.CheckboxInput() )
多選checkbox
class LoginForm(forms.Form): ... hobby = forms.fields.MultipleChoiceField( choices=((1, "籃球"), (2, "足球"), (3, "雙色球"),), label="愛好", initial=[1, 3], widget=forms.widgets.CheckboxSelectMultiple() )
在使用選擇標籤時,須要注意choices的選項能夠從數據庫中獲取,可是因爲是靜態字段 ***獲取的值沒法實時更新***(由於對象已經提早生成了,要重寫構造函數),那麼須要自定義構造方法從而達到此目的。
方式一:
from django.forms import Form from django.forms import widgets from django.forms import fields class MyForm(Form): user = fields.ChoiceField( # choices=((1, '上海'), (2, '北京'),), initial=2, widget=widgets.Select ) def __init__(self, *args, **kwargs): super(MyForm,self).__init__(*args, **kwargs) # self.fields['user'].choices = ((1, '上海'), (2, '北京'),) # 或 self.fields['user'].choices = models.Classes.objects.all().values_list('id','caption')
方式二:
from django import forms from django.forms import fields from django.forms import models as form_model class FInfo(forms.Form): authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all()) # 多選 # authors = form_model.ModelChoiceField(queryset=models.NNewType.objects.all()) # 單選
Field required=True, 是否容許爲空 widget=None, HTML插件 label=None, 用於生成Label標籤或顯示內容 initial=None, 初始值 help_text='', 幫助信息(在標籤旁邊顯示) error_messages=None, 錯誤信息 {'required': '不能爲空', 'invalid': '格式錯誤'} validators=[], 自定義驗證規則 localize=False, 是否支持本地化 disabled=False, 是否能夠編輯 label_suffix=None Label內容後綴 CharField(Field) max_length=None, 最大長度 min_length=None, 最小長度 strip=True 是否移除用戶輸入空白 IntegerField(Field) max_value=None, 最大值 min_value=None, 最小值 FloatField(IntegerField) ... DecimalField(IntegerField) max_value=None, 最大值 min_value=None, 最小值 max_digits=None, 總長度 decimal_places=None, 小數位長度 BaseTemporalField(Field) input_formats=None 時間格式化 DateField(BaseTemporalField) 格式:2015-09-01 TimeField(BaseTemporalField) 格式:11:12 DateTimeField(BaseTemporalField)格式:2015-09-01 11:12 DurationField(Field) 時間間隔:%d %H:%M:%S.%f ... RegexField(CharField) regex, 自定製正則表達式 max_length=None, 最大長度 min_length=None, 最小長度 error_message=None, 忽略,錯誤信息使用 error_messages={'invalid': '...'} EmailField(CharField) ... FileField(Field) allow_empty_file=False 是否容許空文件 ImageField(FileField) ... 注:須要PIL模塊,pip3 install Pillow 以上兩個字典使用時,須要注意兩點: - form表單中 enctype="multipart/form-data" - view函數中 obj = MyForm(request.POST, request.FILES) URLField(Field) ... BooleanField(Field) ... NullBooleanField(BooleanField) ... ChoiceField(Field) ... choices=(), 選項,如:choices = ((0,'上海'),(1,'北京'),) required=True, 是否必填 widget=None, 插件,默認select插件 label=None, Label內容 initial=None, 初始值 help_text='', 幫助提示 ModelChoiceField(ChoiceField) ... django.forms.models.ModelChoiceField queryset, # 查詢數據庫中的數據 empty_label="---------", # 默認空顯示內容 to_field_name=None, # HTML中value的值對應的字段 limit_choices_to=None # ModelForm中對queryset二次篩選 ModelMultipleChoiceField(ModelChoiceField) ... django.forms.models.ModelMultipleChoiceField TypedChoiceField(ChoiceField) coerce = lambda val: val 對選中的值進行一次轉換 empty_value= '' 空值的默認值 MultipleChoiceField(ChoiceField) ... TypedMultipleChoiceField(MultipleChoiceField) coerce = lambda val: val 對選中的每個值進行一次轉換 empty_value= '' 空值的默認值 ComboField(Field) fields=() 使用多個驗證,以下:即驗證最大長度20,又驗證郵箱格式 fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),]) MultiValueField(Field) PS: 抽象類,子類中能夠實現聚合多個字典去匹配一個值,要配合MultiWidget使用 SplitDateTimeField(MultiValueField) input_date_formats=None, 格式列表:['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y'] input_time_formats=None 格式列表:['%H:%M:%S', '%H:%M:%S.%f', '%H:%M'] FilePathField(ChoiceField) 文件選項,目錄下文件顯示在頁面中 path, 文件夾路徑 match=None, 正則匹配 recursive=False, 遞歸下面的文件夾 allow_files=True, 容許文件 allow_folders=False, 容許文件夾 required=True, widget=None, label=None, initial=None, help_text='' GenericIPAddressField protocol='both', both,ipv4,ipv6支持的IP格式 unpack_ipv4=False 解析ipv4地址,若是是::ffff:192.0.2.1時候,可解析爲192.0.2.1, PS:protocol必須爲both才能啓用 SlugField(CharField) 數字,字母,下劃線,減號(連字符) ... UUIDField(CharField) uuid類型
下述UserForm均爲下面的UserForm
class Userform(models.Model): username=models.CharField(max_length=32) password=models.CharField(max_length=32)
form = UserFrom(request.POST) # {"username":"wlx","password":"123"} if form.is_valid():
校驗規則:
根據UserForm類進行校驗,對應字段進行校驗,返回布爾值,所有正確返回True,不然返回False
校驗時,input框中name屬性值必定要和UserForm中字段名相同,不然沒法校驗,用form組件生成時會自動同一,本身寫時要注意
這裏UserForm只有username和password,傳入時多傳則多的不匹配,只要相應的能匹配上,無論多傳的是啥,都是True,可是少傳必定返回False
校驗規則能夠自定義
在通過is_valid()進行校驗完成後,經過校驗的信息放在clean_data中,沒有經過校驗的信息放在errors中
if form.is_valid(): # 按UserForm類進行校驗,返回布爾值,所有經過才返回True print(form.cleaned_data) # 全部乾淨的字段以及對應的值 else: print(form.cleaned_data) # print(form.errors) # ErrorDict : {"校驗錯誤的字段":["錯誤信息",]} print(form.errors.get("name")) # ErrorList ["錯誤信息",]
模型:models.py
class UserInfo(models.Model): name=models.CharField(max_length=32) pwd=models.CharField(max_length=32) email=models.EmailField() tel=models.CharField(max_length=32)
模板: register.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} <div> <label for="user">用戶名</label> <p><input type="text" name="name" id="name"></p> </div> <div> <label for="pwd">密碼</label> <p><input type="password" name="pwd" id="pwd"></p> </div> <div> <label for="r_pwd">確認密碼</label> <p><input type="password" name="r_pwd" id="r_pwd"></p> </div> <div> <label for="email">郵箱</label> <p><input type="text" name="email" id="email"></p> </div> <input type="submit"> </form> </body> </html>
視圖函數:register
# forms組件 from django.forms import widgets wid_01=widgets.TextInput(attrs={"class":"form-control"}) wid_02=widgets.PasswordInput(attrs={"class":"form-control"}) class UserForm(forms.Form): name=forms.CharField(max_length=32, widget=wid_01 ) pwd=forms.CharField(max_length=32,widget=wid_02) r_pwd=forms.CharField(max_length=32,widget=wid_02) email=forms.EmailField(widget=wid_01) tel=forms.CharField(max_length=32,widget=wid_01) def register(request): if request.method=="POST": form=UserForm(request.POST) if form.is_valid(): # 按UserForm類進行校驗,返回布爾值,所有經過才返回True print(form.cleaned_data) # 全部乾淨的字段以及對應的值 else: print(form.cleaned_data) # print(form.errors) # ErrorDict : {"校驗錯誤的字段":["錯誤信息",]} print(form.errors.get("name")) # ErrorList ["錯誤信息",] return HttpResponse("OK") form=UserForm() return render(request,"register.html",locals())
方式一:
from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.validators import RegexValidator class MyForm(Form): user = fields.CharField( validators=[RegexValidator(r'^[0-9]+$', '請輸入數字'), RegexValidator(r'^159[0-9]+$', '數字必須以159開頭')], )
方式二:
import re from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.exceptions import ValidationError # 自定義驗證規則 def mobile_validate(value): mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$') if not mobile_re.match(value): raise ValidationError('手機號碼格式錯誤') class PublishForm(Form): title = fields.CharField(max_length=20, min_length=5, error_messages={'required': '標題不能爲空', 'min_length': '標題最少爲5個字符', 'max_length': '標題最多爲20個字符'}, widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': '標題5-20個字符'})) # 使用自定義驗證規則 phone = fields.CharField(validators=[mobile_validate, ], error_messages={'required': '手機不能爲空'}, widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': u'手機號碼'})) email = fields.EmailField(required=False, error_messages={'required': u'郵箱不能爲空','invalid': u'郵箱格式錯誤'}, widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': u'郵箱'}))
# forms組件 from django.forms import widgets wid_01=widgets.TextInput(attrs={"class":"form-control"}) wid_02=widgets.PasswordInput(attrs={"class":"form-control"}) from django.core.exceptions import ValidationError class UserForm(forms.Form): name=forms.CharField(max_length=32, widget=wid_01 ) pwd=forms.CharField(max_length=32,widget=wid_02) r_pwd=forms.CharField(max_length=32,widget=wid_02) email=forms.EmailField(widget=wid_01) tel=forms.CharField(max_length=32,widget=wid_01) # 局部鉤子 def clean_name(self): val=self.cleaned_data.get("name") if not val.isdigit(): return val else: raise ValidationError("用戶名不能是純數字!") # 全局鉤子 def clean(self): pwd=self.cleaned_data.get("pwd") r_pwd=self.cleaned_data.get("r_pwd") if pwd==r_pwd: return self.cleaned_data else: raise ValidationError('兩次密碼不一致!') def register(request): if request.method=="POST": form=UserForm(request.POST) if form.is_valid(): print(form.cleaned_data) # 全部乾淨的字段以及對應的值 else: clean_error=form.errors.get("__all__") return render(request,"register.html",locals()) form=UserForm() return render(request,"register.html",locals())
<form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div> <label for="">{{ field.label }}</label> {{ field }} <span class="pull-right" style="color: red"> {% if field.label == 'R pwd' %} <span>{{ clean_error.0 }}</span> {% endif %} {{ field.errors.0 }} </span> </div> {% endfor %} <input type="submit" class="btn btn-default"> </form>
應用Bootstrap樣式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css"> <title>login</title> </head> <body> <div class="container"> <div class="row"> <form action="/login2/" method="post" novalidate class="form-horizontal"> {% csrf_token %} <div class="form-group"> <label for="{{ form_obj.username.id_for_label }}" class="col-md-2 control-label">{{ form_obj.username.label }}</label> <div class="col-md-10"> {{ form_obj.username }} <span class="help-block">{{ form_obj.username.errors.0 }}</span> </div> </div> <div class="form-group"> <label for="{{ form_obj.pwd.id_for_label }}" class="col-md-2 control-label">{{ form_obj.pwd.label }}</label> <div class="col-md-10"> {{ form_obj.pwd }} <span class="help-block">{{ form_obj.pwd.errors.0 }}</span> </div> </div> <div class="form-group"> <label class="col-md-2 control-label">{{ form_obj.gender.label }}</label> <div class="col-md-10"> <div class="radio"> {% for radio in form_obj.gender %} <label for="{{ radio.id_for_label }}"> {{ radio.tag }}{{ radio.choice_label }} </label> {% endfor %} </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button type="submit" class="btn btn-default">註冊</button> </div> </div> </form> </div> </div> <script src="/static/jquery-3.2.1.min.js"></script> <script src="/static/bootstrap/js/bootstrap.min.js"></script> </body> </html> Django form應用Bootstrap樣式簡單示例
批量添加樣式
可經過重寫form類的init方法來實現。
class LoginForm(forms.Form): username = forms.CharField( min_length=8, label="用戶名", initial="張三", error_messages={ "required": "不能爲空", "invalid": "格式錯誤", "min_length": "用戶名最短8位" } ... def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' })
這個組件的功能就是把model和form組合起來,實現代碼的優化
#首先導入ModelForm from django.forms import ModelForm #在視圖函數中,定義一個類,好比就叫StudentList,這個類要繼承ModelForm,在這個類中再寫一個原類Meta(規定寫法,並注意首字母是大寫的) #在這個原類中,有如下屬性(部分): class StudentList(ModelForm): class Meta: model =Student #對應的Model中的類 fields = "__all__" #字段,若是是__all__,就是表示列出全部的字段 exclude = None #排除的字段 #error_messages用法: error_messages = { 'name':{'required':"用戶名不能爲空",}, 'age':{'required':"年齡不能爲空",}, } #widgets用法,好比把輸入用戶名的input框給爲Textarea #首先得導入模塊 from django.forms import widgets as wid #由於重名,因此起個別名 widgets = { "name":wid.Textarea(attrs={"class":"c1"}) #還能夠自定義屬性 } #labels,自定義在前端顯示的名字 labels= { "name":"用戶名" }
class Meta:下經常使用參數:參數不少是字典,對應表的各個字段,基本是{字段:值}
model = models.Student # 對應的Model中的類 fields = "__all__" # 字段,若是是__all__,就是表示列出全部的字段 exclude = None # 排除的字段 labels = None # 提示信息 help_texts = None # 幫助提示信息 widgets = None # 自定義插件 error_messages = None # 自定義錯誤信息
而後在url對應的視圖函數中實例化這個類,把這個對象傳給前端
def student(request): if request.method == 'GET': student_list = StudentList() # 實例化modelform類,按照mata中model進行實例化 return render(request,'student.html',{'student_list':student_list})
而後前端只須要 {{ student_list.as_p }} 一下,全部的字段就都出來了,能夠用as_p顯示所有,也能夠經過for循環這student_list,拿到的是一個個input框,如今咱們就不用as_p,手動把這些input框搞出來,as_p拿到的頁面太醜。
首先 for循環這個student_list,拿到student對象,直接在前端打印這個student,是個input框student.label ,拿到數據庫中每一個字段的verbose_name ,若是沒有設置這個屬性,拿到的默認就是字段名,還能夠經過student.errors.0 拿到錯誤信息有了這些,咱們就能夠經過bootstrap,本身拼出來想要的樣式了,好比:
<body> <div class="container"> <h1>student</h1> <form method="POST" novalidate> {% csrf_token %} {# {{ student_list.as_p }}#} # 這種能夠直接拿出數據 {% for student in student_list %} # 也可使用for循環 <div class="form-group col-md-6"> {# 拿到數據字段的verbose_name,沒有就默認顯示字段名 #} <label class="col-md-3 control-label">{{ student.label }}</label> <div class="col-md-9" style="position: relative;">{{ student }}</div>
<span>{{ student.errors.0 }}</span> # 取出錯誤信息 </div> {% endfor %} <div class="col-md-2 col-md-offset-10"> <input type="submit" value="提交" class="btn-primary"> </div> </form> </div> </body>
如今還缺一個input框的form-contral樣式,能夠考慮在後臺的widget裏面添加,好比這樣:
from django.forms import widgets as wid #由於重名,因此起個別名 widgets = { "name":wid.TextInput(attrs={'class':'form-control'}), "age":wid.NumberInput(attrs={'class':'form-control'}), "email":wid.EmailInput(attrs={'class':'form-control'}),
"date":wid.TextInput(attrs={'class':'form-control','type':'date'}), #時間組件沒有DateInput,由於給前端都是字符串,要在屬性里加type:date纔有日期組件效果 }
注意:時間組件沒有DateInput,由於給前端都是字符串,要在屬性里加type:date纔有日期組件效果
保存數據的時候,不用挨個取數據了,只須要save一下,由於知道是按照什麼表保存,字段有哪些,因此直接save便可
def student(request): if request.method == 'GET': student_list = StudentList() # 不傳數據進行實例化 return render(request,'student.html',{'student_list':student_list}) else: student_list = StudentList(request.POST) # 將數據直接傳進去進行實例化 if student_list.is_valid(): student_list.save() # 根據post請求的數據給指定表添加了一行數據 return redirect(request,'student_list.html',{'student_list':student_list})
若是不用ModelForm,編輯的時候得顯示以前的數據吧,還得挨個取一遍值,若是ModelForm,只須要加一個instance=obj(obj是要修改的數據庫的一條數據的對象)就能夠獲得一樣的效果
保存的時候要注意,必定要注意有這個對象(instance=obj),不然不知道更新哪個數據,代碼示例:
from django.shortcuts import render,HttpResponse,redirect from django.forms import ModelForm # Create your views here. from app01 import models def test(request): # model_form = models.Student model_form = models.Student.objects.all() return render(request,'test.html',{'model_form':model_form}) class StudentList(ModelForm): class Meta: model = models.Student #對應的Model中的類 fields = "__all__" #字段,若是是__all__,就是表示列出全部的字段 exclude = None #排除的字段 labels = None #提示信息 help_texts = None #幫助提示信息 widgets = None #自定義插件 error_messages = None #自定義錯誤信息 #error_messages用法: error_messages = { 'name':{'required':"用戶名不能爲空",}, 'age':{'required':"年齡不能爲空",}, } #widgets用法,好比把輸入用戶名的input框給爲Textarea #首先得導入模塊 from django.forms import widgets as wid #由於重名,因此起個別名 widgets = { "name":wid.Textarea } #labels,自定義在前端顯示的名字 labels= { "name":"用戶名" } def student(request): # 添加數據還仍是直接save就能夠 if request.method == 'GET': student_list = StudentList() return render(request,'student.html',{'student_list':student_list}) else: student_list = StudentList(request.POST) if student_list.is_valid(): student_list.save() return render(request,'student.html',{'student_list':student_list}) def student_edit(request,pk): # 修改數據的時候須要注意,實例化時要傳instance實例化表中一行數據 obj = models.Student.objects.filter(pk=pk).first() # 根據傳入pk實例化obj if not obj: return redirect('test') if request.method == "GET": # get請求把一行數據內容反映在前端上,不傳instance前端都是默認數據 student_list = StudentList(instance=obj) return render(request,'student_edit.html',{'student_list':student_list}) else: # 實例化時要傳post參數和實例對象,這樣就至關於修改了要修改的那一行 student_list = StudentList(request.POST,instance=obj) if student_list.is_valid(): student_list.save() # 實例化的時候指定了哪一行以後,save就會修改那一行,不然是從新添加新數據 return render(request,'student_edit.html',{'student_list':student_list})
總結: 從上邊能夠看到ModelForm用起來是很是方便的,好比增長修改之類的操做。可是也帶來額外很差的地方,model和form之間耦合了。若是不耦合的話,mf.save()方法也沒法直接提交保存。 可是耦合的話使用場景一般侷限用於小程序,寫大程序就最好不用了。