Django ModelForm 组件的应用
ModelForm組件的應用
ModelForm 組件的創建:?
1.創建一個類,該類繼承 forms.ModelForm?
2.大致組成部分
class ModelNameModelForm(forms.ModelForm):
class Meta:
model =需要校正的模型類名
例:model = models.Book
fields=" __all__"? 或? fields=["字段名”,........]? ? 選擇需要展示或校正的字段
error_messages={
"字段名”:{“required”: "此字段不能為空”},
"字段名”:{“required”: "此字段不能為空”},
.........
}
from django.forms import? widgets as wid
widgets={
"字段名":wid.TextInput(attrs={"input標簽屬性":"屬性值"}),
"price":wid.TextInput(attrs={"class":"form-control"}),
"pub_date":wid.DateInput(attrs={"class":"form-control","type":"date"}),
}
labels={
"字段名”:“別名”,
“title” :“書籍名稱”,
}
#鉤子,進一步校正函數
def??clean_字段名(self):
val = self.cleaned_data.get("字段名”)
if? 符合條件:
return? val
else:
raise? ValidationError("想要說明的錯誤信息”)
3.應用
用的時候只需要? :
form =?ModelNameModelForm(需要校正的數據字典)
例:
?
1.直接展示空的input的標簽(get請求時)
form = BookModelForm( )? ?#直接展示,渲染出空內容的input 標簽?
#? form = BookModelForm(instance=edit_book)? ?編輯情況下
?
2.用戶提交數據,需校正時,可以展示錯誤的提示信息 (post請求時)
form =?BookModelForm(request.POST )? ? #校正前端通過post請求的提交的數據?
##form = BookModelForm(request.POST,instance=edit_book)? ?編輯情況下
if? form.is_vaild():
form.save()
redirect("/book/")
else:
return render(request, 'addbook.html', locals())
?
實例
1.model .py :(模型類? Book為例)
from django.db import models# Create your models here. from django.db import models# Create your models here. class Book(models.Model):title = models.CharField( max_length=32,verbose_name="書籍名稱")pub_date=models.DateField(verbose_name="出版日期")price=models.DecimalField(max_digits=5,decimal_places=2,verbose_name="價格")publish=models.ForeignKey(to="Publish",to_field="id",on_delete=models.CASCADE,null=True,verbose_name="出版社")authors=models.ManyToManyField("Author",db_table="book2authors",verbose_name="作者") # 創建關系表def __str__(self):return self.titleclass Meta:verbose_name="書籍"?
2.views.py(構建ModelForm組件)
?
form django import? forms
from django.forms import? widgets as wid
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError class BookModelForm(forms.ModelForm):class Meta:model = models.Bookfields="__all__" #默認頁面渲染時 顯示所有的字段# fields=["title","price"] #需要顯示的字段#錯誤信息error_messages={"title":{"required":"書名不能為空"},"price":{"required":"價格不能為空"},"pub_date":{"required":"日期不能為空"},"publish":{"required":"出版社不能為空"},"authors":{"required":"作者不能為空"},}
#給渲染的input標簽設置type類型和相關的屬性
widgets={"title":wid.TextInput(attrs={"class":"form-control"}),"price":wid.TextInput(attrs={"class":"form-control"}),"pub_date":wid.DateInput(attrs={"class":"form-control","type":"date"}),}
#字段別名設置labels={"title":"書籍名稱",
}
#鉤子函數,進一步進行約束
#對title字段進行約束def clean_title(self):val=self.cleaned_data.get("title")if val.isdigit():raise ValidationError("書名不能為純數字!")else:return val
#對price字段進行約束
def clean_price(self):
val=self.cleaned_data.get("price")
if val.isdigit():
return val
else:
raise ValidationError("價格必須為數字")
3.views.py視圖函數中:
后端添加視圖函數:用ModelForm組件實現頁面渲染 (紅色字體部分)
def addbook(request):if request.method=="POST":'''data=request.POST.dict()data.pop("csrfmiddlewaretoken")data.pop("author_list")book=models.Book.objects.create(**data) # 保證提交鍵值對的鍵必須和數據庫表字段一致# 為書籍綁定作者關系author_list=request.POST.getlist("author_list")print(author_list) # ['1', '2']book.authors.add(*author_list)'''form=BookModelForm(request.POST)if form.is_valid():form.save()return redirect("/books/")else:return render(request, 'addbook.html', locals())else:# form=BookForm() # forms組件form=BookModelForm() # modelforms組件return render(request,'addbook.html',locals())前端添加頁面:
<div class="container-fluid"><div class="row"><div class="col-md-6 col-md-offset-3"><h3>添加{{ table_name }}</h3><form action="" method="post" novalidate>{% csrf_token %}{% for field in form %}<div><label for="">{{ field.label }}</label>{{ field }}<span class="error pull-right">{{ field.errors.0 }}</span></div>{% endfor %}<input type="submit" class="btn btn-primary"></form></div></div> </div>后端編輯視圖:
def editbook(request,edit_book_id):edit_book = models.Book.objects.filter(pk=edit_book_id).first()if request.method=="POST":# 方式1:# title=request.POST.get("title")# price=request.POST.get("price")# pub_date=request.POST.get("pub_date")# publish_id=request.POST.get("publish_id")# author_list=request.POST.getlist("author_list")# models.Book.objects.filter(pk=edit_book_id).update(title=title,price=price,pub_date=pub_date,publish_id=publish_id) # update只有queryset才能調用# edit_book.authors.set(author_list)# 方式2:# data=request.POST.dict()# data.pop("csrfmiddlewaretoken")# author_list=data.pop("author_list")# models.Book.objects.filter(pk=edit_book_id).update(**data) # 保證提交鍵值對的鍵必須和數據庫表字段一致# # 為書籍綁定作者關系# author_list=request.POST.getlist("author_list")# edit_book.authors.set(author_list)# 方式3form = BookModelForm(request.POST,instance=edit_book)#編輯時,instance=edit_book 傳進去就可以該對象信息在頁面的展示,這是編輯和添加頁面的區別之處if form.is_valid():,form.save()return redirect("/books/")else:return render(request, 'editbook.html', locals())else:form=BookModelForm(instance=edit_book)return render(request,'editbook.html',locals())前端編輯頁面渲染代碼:
<div class="container-fluid"><div class="row"><div class="col-md-6 col-md-offset-3"><h3>編輯{{ table_name }}</h3><form action="" method="post" novalidate>{% csrf_token %}{% for field in form %}<div><label for="">{{ field.label }}</label>{{ field }}<span class="error pull-right">{{ field.errors.0 }}</span></div>{% endfor %}<input type="submit" class="btn btn-primary"></form></div></div> </div>?
?
轉載于:https://www.cnblogs.com/knighterrant/p/10279659.html
總結
以上是生活随笔為你收集整理的Django ModelForm 组件的应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: maven的下载
- 下一篇: Sqluldr2 libclnts