Django框架【form组件】

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>
上一篇:前端系列之CSS基础知识概述


下一篇:[编织消息框架][JAVA核心技术]动态代理应用2