"""
2.form组件介绍
演示form本质应用
class TestForm(forms.Form):
name = forms.CharField(max_length=32)
email = forms.EmailField()
age = forms.IntegerField()
python console中直接测试
from app01 import views
obj = views.TestForm({'name':'jason','email':'123','age':18})
obj.is_valid() # 校验数据
False
obj.cleaned_data # 合格的放入这个里面
{'name': 'jason', 'age': 18}
obj.errors # 不合格的放入errors中
{'email': ['Enter a valid email address.']}
继续演示几种传参类型
obj = views.TestForm({'name':'jason','age':18})
obj = views.TestForm({'name':'jason','email':"[email protected]",'age':18})
obj = views.TestForm({'name':'jason','email':"[email protected]",'age':18,'abc':123})
3.form组件完成
class Book(models.Model):
title = models.CharField(max_length=32)
price = models.DecimalField(max_digits=8,decimal_places=2)
date = models.DateField()
publish = models.ForeignKey("Publish")
authors = models.ManyToManyField("Author")
class Publish(models.Model):
name = models.CharField(max_length=32)
class Author(models.Model):
name = models.CharField(max_length=32)
对上述三张表用form完成增 >>> 编辑功能form组件书写难度
1.新建django项目 自定义模型表
这里详细演戏图书管理系统的增删改查:
1.先不借助任何组件,自己手动渲染标签
这里需要注意的问题有前端input标签一定要写name属性
后端在更新数据的时候,记得用关键字传参的形式去做
新增用add(*author) 编辑用set(author)
2.借助form组件
前端三种渲染方式
3.最后推到出modelform组件
class BookModelForm(forms.ModelForm):
class Meta:
model = models.Book
fields = '__all__'
4.modelform介绍
"""
"""
1.modelform完成CRM项目中模型表的增删改查
这里为什么定义这个方法,主要是用户如果想针对自己的模型表进行其他的特定操作
def get_model_form(self):
if self.model_form_class:
return self.model_form_class
from django.forms import ModelForm
class ModelFormClass(ModelForm):
class Meta:
model = self.model
fields = '__all__'
return ModelFormClass
def add_view(self,request):
model_form = self.get_model_form()
if request.method == 'POST':
model_form_obj = model_form(request.POST)
if model_form_obj.is_valid():
model_form_obj.save()
return redirect(self.get_reverse_url('list'))
model_form_obj = model_form()
return render(request,'stark/add_view.html',locals())
def edit_view(self,request,id):
model_form = self.get_model_form()
edit_obj = self.model.objects.filter(pk=id).first()
if request.method == 'POST':
model_form_obj = model_form(request.POST,instance=edit_obj)
if model_form_obj.is_valid():
model_form_obj.save()
return redirect(self.get_reverse_url('list'))
model_form_obj = model_form(instance=edit_obj)
return render(request,'stark/edit_view.html',locals())
def delete_view(self,request,id):
delete_obj = self.model.objects.filter(pk=id).delete()
return redirect(self.get_reverse_url('list'))
"""
分页
"""
1.批量插入数据方法
传统:效率极低
def index(request):
for i in range(100):
Book.objects.create(title='book_%s'%i,price=i*i)
return render(request,'book_list.html')
现在:
book_list = [] # 里面方法Book对象
for i in range(100):
book = Book(title="book_%s"%i,price=i*i)
book_list.append(book)
Book.objects.bulk_create(book_list)
2.展示批量产生的数据
3.分页介绍
博客园分页代码拷贝,解释
保存搜索条件介绍(拉勾网展示)
request.GET.urlencoded()构造get请求携带数据格式
"""