# 增删改查 # 前端提交数据的方式: # ajax|form表单 # 前端数据校验,为了减小服务器不必要的压力; # 后端验证是为了保证后端数据的准确性; # 因为表格中数据都是在后端simple_tag生成的,所以需要在simple_tag循环代码中, # 将下标为0的字段值上加上链接,点击可以跳转至内容修改页面; # kingadmin_tags.py @register.simple_tag def build_table_row(obj,admin_class): ele = "" if admin_class.list_display: for index,column_name in enumerate(admin_class.list_display): column_obj = admin_class.model._meta.get_field(column_name) if column_obj.choices: #get_xxx_display column_data = getattr(obj,‘get_%s_display‘% column_name)() else: column_data = getattr(obj,column_name) td_ele = "<td>%s</td>"% column_data # 如果index为0时,为该字段值添加上链接 if index == 0: td_ele = "<td><a href=‘%s/change/‘></a>%s</td>"% (obj.id,column_data) ele += td_ele else: td_ele = "<td><a href=‘%s/change/‘>%s</a></td>"% (obj.id,obj) ele += td_ele return mark_safe(ele) # 配置链接的urlconf # urls.py url(r‘^/(\w+)/(\w+)/(\d+)/change/$‘, views.table_obj_change, name="table_obj_change"), # views.py @login_required def table_obj_change(request,app_name,model_name,obj_id): """数据修改页面""" return render(request, ‘kingadmin/table_obj_change.html‘) # table_obj_change.html {% extends ‘kingadmin/index.html‘ %} {% load kingadmin_tag %} {% block right_content %} The content for urself! <div> 修改页面! </div> {% endblock right_content %} # 静态model_form回顾 # forms.py class CustomerForm(ModelForm): class Meta: model = models.CustomerInfo fields = ‘__all__‘ #[‘name‘,‘consultant‘,‘status‘] # views.py @login_required def table_obj_change(request,app_name,model_name,obj_id): """数据修改页面""" from crm import forms form = forms.CustomerForm() return render(request, ‘kingadmin/table_obj_change.html‘,locals()) # form数据就在页面中显示,但是所有表页面显示这一个modelform指定的表字段; # 难道每个表都写一个modelform? # 怎么做成动态modelform?django里没有动态modelform的概念; # 动态生成类? # 创建类的另一种方式 def func(self): # 记得加self print(‘hello world‘) Foo = type(‘Foo‘,(object,),{‘func‘:func}) # 参数1:类名; # 参数2:当前类的基类; # 参数3:类的成员; # 实现动态生成指定表的所有表结构modelform # form_handle.py # class CustomerForm(ModelForm): # """展示所有表结构""" # class Meta: # model = models.CustomerInfo # fields = ‘__all__‘ #[‘name‘,‘consultant‘,‘status‘] def create_dynamic_modelform(admin_class): """动态生成modelform""" class Meta: model = admin_class.model fields = "__all__" dynamic_form = type("DynamicModelForm",(ModelForm,),{‘Meta‘:Meta}) print(dynamic_form) # >> <class ‘django.forms.widgets.DynamicModelForm‘> return dynamic_form # 返回类,来实例化 # veiws.py @login_required def table_obj_change(request,app_name,model_name,obj_id): """数据修改页面""" # 1.动态创建modelform类 admin_class = site.enabled_admins[app_name][model_name] modelform = form_handle.create_dynamic_modelform(admin_class) # 2.实现modelform,展示表结构 form_obj = modelform() return render(request, ‘kingadmin/table_obj_change.html‘,locals()) # modelform添加自定义样式 # <div class="form-group"> # <label for="inputEmail3" class="col-sm-2 control-label">Email</label> # <div class="col-sm-10"> # <input type="email" class="form-control" id="inputEmail3" placeholder="Email"> # </div> # </div> # table_obj_change.html <form class="form-horizontal"> {% for field in form_obj %} <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">{{ field.label }}</label> <div class="col-sm-10"> {{ field }} </div> </div> {% endfor %} </form> # {{field.label}} 自动生成了input样式,怎么修改? # 修改modelform样式 # form_handle.py def create_dynamic_modelform(admin_class): """动态生成modelform""" class Meta: model = admin_class.model fields = "__all__" def __new__(cls,*args,**kwargs): print("__new__",cls,args,kwargs) for field_name in cls.base_fields: field_obj = cls.base_fields[field_name] field_obj.widget.attrs.update({‘class‘:‘form-control‘}) return ModelForm.__new__(cls) dynamic_form = type("DynamicModelForm",(ModelForm,),{‘Meta‘:Meta,‘__new__‘:__new__}) print(dynamic_form) return dynamic_form # 任意表的增删改查 # 1.修改 # 1.1 展示当前修改表与记录 # table_obj_change.html <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <!-- 1.获取当前表名 --> <h1>{% get_model_name admin_class %}</h1> <!-- 2.显示当前修改哪条记录 --> 当前记录:{{ form_obj.instance }} </div> </nav> # views.py @login_required def table_obj_change(request,app_name,model_name,obj_id): """数据修改页面""" # 1.动态创建modelform类 admin_class = site.enabled_admins[app_name][model_name] modelform = form_handle.create_dynamic_modelform(admin_class) # 2.实现modelform,展示表结构 # 2.1 展示没有数据的modelform # form_obj = modelform() # 2.2 展示当前数据的modelform # 获取当前记录对象 obj = admin_class.model.objects.get(id=obj_id) form_obj = modelform(instance=obj) return render(request, ‘kingadmin/table_obj_change.html‘,locals()) # 提交修改后的表单model_form <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Sign in</button> </div> </div> # 1.2 提交以及保存修改后的数据 # views.py @login_required def table_obj_change(request,app_name,model_name,obj_id): """数据修改页面""" # 1.动态创建modelform类 admin_class = site.enabled_admins[app_name][model_name] modelform = form_handle.create_dynamic_modelform(admin_class) # 2.实现modelform,展示表结构 # 2.1 展示没有数据的modelform # form_obj = modelform() # 2.2 展示当前数据的modelform # 获取当前记录对象 obj = admin_class.model.objects.get(id=obj_id) # 3.判断请求条件,如果是POST请求,获取请求数据,进行数据检验,再做保存,验证不通过,返回错误信息; if request.method == ‘GET‘: form_obj = modelform(instance=obj) elif request.method == ‘POST‘: form_obj = modelform(instance=obj,data=request.POST) if form_obj.is_valid(): form_obj.save() return redirect(‘/kingadmin/%s/%s‘%(app_name,model_name)) return render(request, ‘kingadmin/table_obj_change.html‘,locals()) # table_obj_change.html <form class="form-horizontal" method="POST"> {% csrf_token %} <!-- modelform全局错误信息 --> {# {{ form_obj.errors }}#} {% for field in form_obj %} <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">{{ field.label }}</label> <div class="col-sm-10"> {{ field }} <!-- 单字段错误信息 --> <span style="color:red">{{ field.errors.0 }}</span> </div> </div> {% endfor %} <div class="form-group"> <div class="col-sm-offset-11 col-sm-10"> <button type="submit" class="btn btn-default">SAVE</button> </div> </div> </form> # 2.增加 # urls.py url(r‘^(\w+)/(\w+)/add/$‘, views.table_obj_add, name="table_obj_add"), # views.py @login_required def table_obj_add(request,app_name,model_name): """增加记录""" # 1.动态创建modelform类 admin_class = site.enabled_admins[app_name][model_name] modelform = form_handle.create_dynamic_modelform(admin_class) if request.method == ‘GET‘: form_obj = modelform() elif request.method == ‘POST‘: form_obj = modelform(data=request.POST) if form_obj.is_valid(): form_obj.save() return redirect(‘/kingadmin/%s/%s‘ % (app_name, model_name)) return render(request, ‘kingadmin/table_obj_add.html‘, locals()) # table_obj_add.html # table_obj_change.html中的表结构就不重复写了,单独写在table_obj_common.html,其它页面include它; # {% include ‘kingadmin/table_obj_common.html‘ %} {% extends ‘kingadmin/index.html‘ %} {% load kingadmin_tag %} {% block right_content %} <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <!-- 1.获取当前表名 --> <h1>{% get_model_name admin_class %}</h1> <!-- 2.显示当前修改哪条记录 --> <b>添加</b> </div> </nav> {% include ‘kingadmin/table_obj_common.html‘ %} {% endblock right_content %} # 问题:不知道有没添加? # 措施:将最新添加的显示在第一个; # views.py def table_obj_list(request,app_name,model_name): ... querysets = admin_class.model.objects.all().order_by(‘-id‘) ... ############################################################### 修改与添加功能做完了;