本篇文章為大家展示了ModelForm組件怎么在Django中使用,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
創(chuàng)新互聯(lián)是一家專業(yè)提供鎮(zhèn)江企業(yè)網(wǎng)站建設(shè),專注與做網(wǎng)站、成都網(wǎng)站建設(shè)、HTML5、小程序制作等業(yè)務(wù)。10年已為鎮(zhèn)江眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)絡(luò)公司優(yōu)惠進(jìn)行中。一、創(chuàng)建ModelForm
from django.forms import ModelForm from appxx import models from django.forms import widgets as wdt # 因?yàn)橹孛云饌€(gè)別名 #定義一個(gè)類,比如BookForm,這個(gè)類要繼承ModelForm,在這個(gè)類中再寫一個(gè)原類Meta(規(guī)定寫法,注意首字母是大寫的) #在這個(gè)原類中,有以下屬性(部分): class BookForm(ModelForm): class Meta: model = models.Book # 對(duì)應(yīng)的Model中的類 fields = "__all__" # 字段,如果是__all__,就表示列出所有的字段,或者使用列表列出想要的字段 exclude = None # 排除的字段 # error_messages用法 error_messages = { "title": {"required": "書名不能為空"}, "price": {"required": "售價(jià)不能為空"}, } # widgets用法,比如把輸入用戶名的input框給為Textarea widgets = { "name": wdt.Textarea(attrs={"class": "c1"}) # 還可以自定義屬性 } #labels,自定義在前端顯示的名字 labels= { "title": "書名", "price": "售價(jià)", }
然后在 url 對(duì)應(yīng)的視圖函數(shù)中實(shí)例化這個(gè)類,把這個(gè)對(duì)象傳給前端:
def add_book(request): form = forms.BookForm() return render(request, "add_book.html", {"form": form})
然后在前端像Form組件那樣渲染頁(yè)面
二、添加數(shù)據(jù)
保存數(shù)據(jù)的時(shí)候,不用挨個(gè)取數(shù)據(jù)了,只需要 save 一下即可。
from django.shortcuts import render,redirect from appxx import models from appxx import forms def add_book(request): if request.method == "POST": form = forms.BookForm(request.POST) if form.is_valid(): form.save() return redirect("/book/") form = forms.BookForm() return render(request, "add_book.html", {"form": form})
三、編輯數(shù)據(jù)
如果不使用 ModelForm,編輯的時(shí)候得顯示之前的數(shù)據(jù),還得挨個(gè)取一遍值;如果使用 ModelForm,只需要加一個(gè)instance=obj(obj是要修改的數(shù)據(jù)庫(kù)的一條數(shù)據(jù)的對(duì)象)就可以得到同樣的效果。
保存的時(shí)候要注意,一定要注意有這個(gè)對(duì)象(instance=obj),否則不知道更新哪一個(gè)數(shù)據(jù)。
from django.shortcuts import render,redirect from appxx import models from appxx import forms def edit_book(request, edit_book_id): edit_book= models.Book.objects.filter(id=edit_book_id).first() if request.method == "POST": form = forms.BookForm(request.POST, instance=edit_book) if form.is_valid(): form.save() return redirect("/book/") form = forms.BookForm(instance=edit_book) return render(request, "edit_book.html", {"form": form})
總結(jié): 從上邊可以看到 ModelForm 用起來是非常方便的,比如增加修改之類的操作。但是也帶來額外不好的地方,model和form之間耦合了。如果不耦合的話,form.save()方法也無法直接提交保存。 但是耦合的話使用場(chǎng)景通常局限用于小程序,寫大程序就最好不用了。
四、完整示例代碼
項(xiàng)目結(jié)構(gòu)
urls.py
from django.conf.urls import url from django.contrib import admin from appxx import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r"^book/$", views.book), url(r"^book/add/", views.add_book), url(r"^book/edit/(\d+)/", views.edit_book), ]
views.py
from django.shortcuts import render,redirect from appxx import models from appxx import forms def book(request): book_list = models.Book.objects.all() return render(request, "book.html", {"book_list": book_list}) def add_book(request): if request.method == "POST": form = forms.BookForm(request.POST) if form.is_valid(): form.save() return redirect("/book/") form = forms.BookForm() return render(request, "add_book.html", {"form": form}) def edit_book(request, edit_book_id): edit_book= models.Book.objects.filter(id=edit_book_id).first() if request.method == "POST": form = forms.BookForm(request.POST, instance=edit_book) if form.is_valid(): form.save() return redirect("/book/") form = forms.BookForm(instance=edit_book) return render(request, "edit_book.html", {"form": form})
models.py
from django.db import models class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=32) price = models.DecimalField(max_digits=5, decimal_places=2) publish_date = models.DateField() publisher = models.ForeignKey(to="Publisher") authors = models.ManyToManyField(to="Author") def __str__(self): return self.title class Publisher(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=32) def __str__(self): return self.name class Author(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=32) def __str__(self): return self.name
forms.py
from django.forms import ModelForm from appxx import models from django.forms import widgets as wdt class BookForm(ModelForm): class Meta: model = models.Book fields = "__all__" labels = { "title": "書名", "price": "售價(jià)", "publish_date": "出版日期", "publisher": "出版社", "authors": "作者" } widgets = { "title": wdt.TextInput(attrs={"class": "form-control"}), "price": wdt.TextInput(attrs={"class": "form-control"}), "publish_date": wdt.TextInput(attrs={"class": "form-control", "type": "date"}), "publisher": wdt.Select(attrs={"class": "form-control"}), "authors": wdt.SelectMultiple(attrs={"class": "form-control"}), } error_messages = { "title": {"required": "書名不能為空"}, "price": {"required": "售價(jià)不能為空"}, "publish_date": {"required": "出版日期不能為空"}, "publisher": {"required": "出版社不能為空"}, "authors": {"required": "作者不能為空"}, }
book.html
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>展示書籍</title> <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" > </head> <body> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <span><a class="btn btn-primary" href="/book/add/" rel="external nofollow" >添加</a></span> <table class="table table-striped table-bordered"> <thead> <tr> <th>序號(hào)</th> <th>書名</th> <th>售價(jià)</th> <th>出版日期</th> <th>出版社</th> <th>作者</th> <th>操作</th> </tr> </thead> <tbody> {% for book in book_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{ book.title }}</td> <td>{{ book.price }}</td> <td>{{ book.publish_date }}</td> <td>{{ book.publisher.name }}</td> <td> {% for author in book.authors.all %} {{ author.name }} {% endfor %} </td> <td> <span><a class="btn btn-warning" href="/book/edit/{{ book.pk }}/" rel="external nofollow" >編輯</a></span> <span><a class="btn btn-danger" href="">刪除</a></span> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </body> </html>
add_book.html和edit_book.html(兩個(gè)頁(yè)面代碼一樣)
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>添加書籍</title> <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" > <style> .panel-title { font-weight: bolder; } .panel { margin-top: 30px; } </style> </head> <body> <div class="container"> <div class="row"> {# panel開始 #} <div class="panel panel-danger col-sm-6 col-md-6 col-sm-offset-3 col-md-offset-3"> <div class="panel-heading"> <h4 class="panel-title">添加書籍</h4> </div> {# panel-body開始 #} <div class="panel-body"> {# form開始 #} <form class="form-horizontal" action="" method="post" novalidate> {% csrf_token %} <div class="form-group"> <label class="col-md-2 control-label" for="{{ form.title.id_for_label }}">{{ form.title.label }}</label> <div class="col-md-10"> {{ form.title }} </div> </div> <div class="form-group"> <label class="col-md-2 control-label" for="{{ form.price.id_for_label }}">{{ form.price.label }}</label> <div class="col-md-10"> {{ form.price }} </div> </div> <div class="form-group"> <label class="col-md-2 control-label" for="{{ form.publish_date.id_for_label }}">{{ form.publish_date.label }}</label> <div class="col-md-10"> {{ form.publish_date }} </div> </div> <div class="form-group"> <label class="col-md-2 control-label" for="{{ form.publisher.id_for_label }}">{{ form.publisher.label }}</label> <div class="col-md-10"> {{ form.publisher }} </div> </div> <div class="form-group"> <label class="col-md-2 control-label" for="{{ form.authors.id_for_label }}">{{ form.authors.label }}</label> <div class="col-md-10"> {{ form.authors }} </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button type="submit" class="btn btn-success">提交</button> <a class="btn btn-warning pull-right" href="/book/" rel="external nofollow" >取消</a> </div> </div> </form> {# form結(jié)束 #} </div> {# panel-body結(jié)束 #} </div> {# panel結(jié)束 #} </div> </div> </body> </html>
上述內(nèi)容就是ModelForm組件怎么在Django中使用,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
文章名稱:ModelForm組件怎么在Django中使用-創(chuàng)新互聯(lián)
文章網(wǎng)址:http://www.rwnh.cn/article2/ccjcoc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供虛擬主機(jī)、網(wǎng)頁(yè)設(shè)計(jì)公司、網(wǎng)站導(dǎo)航、服務(wù)器托管、關(guān)鍵詞優(yōu)化、商城網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容