Django框架【form元件】
阿新 • • 發佈:2019-01-05
from django.shortcuts import render,redirect # Create your views here. from .models import * from django import forms from django.forms import widgets from django.forms import ModelForm ''' class BookForm(forms.Form): # 原生form email=forms.EmailField() title = forms.CharField(max_length=32,label="書籍名稱") price = forms.DecimalField(max_digits=8, decimal_places=2,label="價格") # 999999.99 date = forms.DateField(label="日期", widget=widgets.TextInput(attrs={"type":"date"}) ) #gender=forms.ChoiceField(choices=((1,"男"),(2,"女"),(3,"其他"))) #publish=forms.ChoiceField(choices=Publish.objects.all().values_list("pk","title")) publish=forms.ModelChoiceField(queryset=Publish.objects.all()) # select authors=forms.ModelMultipleChoiceField(queryset=Author.objects.all()) # select''' from django.forms import widgets as wid class BookForm(ModelForm): class Meta: model=Book fields="__all__" # 部分欄位寫列表 labels={"title":"書籍名稱", "price":"價格"} # 字典 指明欄位 # 設定樣式 widgets={ "title":wid.TextInput(attrs={"class":"form-control"}), "price":wid.TextInput(attrs={"class":"form-control"}), "date":wid.TextInput(attrs={"class":"form-control","type":"date"}), "publish":wid.Select(attrs={"class":"form-control"}), "authors":wid.SelectMultiple(attrs={"class":"form-control"}), } # 錯誤資訊 error_messages={ "title":{"required":"不能為空"} } def books(request): book_list=Book.objects.all() return render(request,"books.html",locals()) def addbook(request): if request.method=="POST": # 新增操作 create form = BookForm(request.POST) if form.is_valid(): # 直接儲存資料 包括跨表操作都已完成 form.save() # form.model.objects.create(request.POST) return redirect("/books/") else: return render(request, "add.html", locals()) form=BookForm() return render(request,"add.html",locals()) def editbook(request,edit_book_id): edit_book = Book.objects.filter(pk=edit_book_id).first() if request.method=="POST": # 修改操作 對instance 這個物件進行update form = BookForm(request.POST,instance=edit_book) if form.is_valid(): form.save() # edit_book.update(request.POST) return redirect("/books/") # get 請求同樣帶著資料過去 # 引數為 instance 物件 form=BookForm(instance=edit_book) return render(request,"edit.html",locals())
form.html
<div class="col-md-4 col-md-offset-2"> <form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div> {{ field.label }} {{ field }} <span class="has-error">{{ field.errors.0 }}</span> </div> {% endfor %} <input type="submit" class="pull-right btn-success btn"> </form> </div>