关于form组件的补充-------formChoice
form组件的Choice字段
还是基于出版社和书的模型来详解
models.py(模型)
from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=32) pub_date = models.DateField() price = models.DecimalField(max_digits=5, decimal_places=2) state=models.IntegerField(choices=((1,'已出版'),(2,'未出版')),default=1) #在数据库存储是以数字存储的,怎么取值?book是类的对象--book.get_state_display publish = models.ForeignKey(to="Publish", to_field="id", on_delete=models.CASCADE, null=True) authors = models.ManyToManyField("Author", db_table="book2authors") # 创建关系表 def __str__(self): return self.title class Publish(models.Model): name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.CharField(max_length=32) def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=32) age = models.IntegerField() gender=models.IntegerField(choices=((1,'男'),(2,'女'),),default=1)#在数据库存储是以数字存储的,怎么取值?book是类的对象--book.get_gender_display
urls.py(路径分发)
urlpatterns = [ path('admin/', admin.site.urls), path('books/', views.books, name='books'), path('addbooks/', views.addbooks, name='addbooks'), re_path('delbooks/(\d+)', views.delbooks), re_path('editbooks/(\d+)', views.editbooks) ]
view.py(视图函数)
#为Book这个模型创建forms,为了渲染数据和校验使用,所以这个类的字段必须和模型类有个逻辑上的关系
class BookForm(forms.Form):
title=forms.CharField(max_length=32)
price= forms.DecimalField(max_digits=5,decimal_places=2)
pub_date = forms.DateField()
state=forms.ChoiceField(choices=((1,'已出版'),(2,'未出版'))) #选择项,用的最多
publish=forms.ModelChoiceField(models.Publish.objects.all()) #一对多
authors=forms.ModelMultipleChoiceField(models.Author.objects.all()) #多对多
#对于publish和author这两个一对多和多对多的字段也不用考虑那么多直接用formChoice字段,然后把所有的对象取出来赋值到里面就行
#查看书籍
def books(request): booklist = models.Book.objects.all() return render(request, 'books.html', {'booklist': booklist})
#添加书籍
def addbooks(request):
# 通过form/ModelForm以及校验标签渲染字段以及输入框
if request.method == 'POST':
form = Bookform(request.POST)
if form.is_valid():
form.save()
return redirect('/books/')
else:
return render(request, 'addbooks.html', {'form': form})
else:
# form=BookForm() #form组件形式,根据字段选择不同的字段类型
return render(request, 'addbooks.html', {'form': form})
#编辑书籍
def editbooks(request, editbook_id):
editbook=models.Book.objects.filter(pk=editbook_id).first()
if request.method == 'POST':
form=BookForm(request.POST)
if form.is_valid():
form.save()
return redirect('/books/')
else:
return render(request,'editbooks.html',{'form':form})
else:
form=BookForm(edit_book)
return render(request,'editbooks.html',{'form':form})