您好,登錄后才能下訂單哦!
本篇文章為大家展示了ModelForm組件怎么在Django中使用,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
一、創建ModelForm
from django.forms import ModelForm from appxx import models from django.forms import widgets as wdt # 因為重名,所以起個別名 #定義一個類,比如BookForm,這個類要繼承ModelForm,在這個類中再寫一個原類Meta(規定寫法,注意首字母是大寫的) #在這個原類中,有以下屬性(部分): class BookForm(ModelForm): class Meta: model = models.Book # 對應的Model中的類 fields = "__all__" # 字段,如果是__all__,就表示列出所有的字段,或者使用列表列出想要的字段 exclude = None # 排除的字段 # error_messages用法 error_messages = { "title": {"required": "書名不能為空"}, "price": {"required": "售價不能為空"}, } # widgets用法,比如把輸入用戶名的input框給為Textarea widgets = { "name": wdt.Textarea(attrs={"class": "c1"}) # 還可以自定義屬性 } #labels,自定義在前端顯示的名字 labels= { "title": "書名", "price": "售價", }
然后在 url 對應的視圖函數中實例化這個類,把這個對象傳給前端:
def add_book(request): form = forms.BookForm() return render(request, "add_book.html", {"form": form})
然后在前端像Form組件那樣渲染頁面
二、添加數據
保存數據的時候,不用挨個取數據了,只需要 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})
三、編輯數據
如果不使用 ModelForm,編輯的時候得顯示之前的數據,還得挨個取一遍值;如果使用 ModelForm,只需要加一個instance=obj(obj是要修改的數據庫的一條數據的對象)就可以得到同樣的效果。
保存的時候要注意,一定要注意有這個對象(instance=obj),否則不知道更新哪一個數據。
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})
總結: 從上邊可以看到 ModelForm 用起來是非常方便的,比如增加修改之類的操作。但是也帶來額外不好的地方,model和form之間耦合了。如果不耦合的話,form.save()方法也無法直接提交保存。 但是耦合的話使用場景通常局限用于小程序,寫大程序就最好不用了。
四、完整示例代碼
項目結構
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": "售價", "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": "售價不能為空"}, "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>序號</th> <th>書名</th> <th>售價</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(兩個頁面代碼一樣)
<!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結束 #} </div> {# panel-body結束 #} </div> {# panel結束 #} </div> </div> </body> </html>
上述內容就是ModelForm組件怎么在Django中使用,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。