django form 和modelform样式设置
目录
1.form通过attr设置属性
2.输入框设置表单状态
3.modelform的使用
4.结合modelform 使用for循环生成输入框
5.基于init构造方法设置样式
6.基本增删改查案例
7.基于ajax和sweetalert实现删除操作
以text input框为例 模板文件需要有bootstrape from django import forms class DepForm(forms.Form): name = forms.CharField(label="部门名称",widget=forms.TextInput(attrs={'class':'form-control'})) #可以添加多个 count = forms.IntegerField(label="部门人数") #IntegerField没有这个属性 def department_add(request): form_obj = DepForm() return render(request,'department_add.html',{'form_obj':form_obj}) 模板文件如下: {% extends 'layout.html' %} {% block content %} <div class="container"> <div style="margin-top: 20px"> <form class="form-horizontal"> <div class="form-group"> <label for="{{ form_obj.name.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.name.label }}</label> <div class="col-sm-8"> {# <input type="email" class="form-control" id="inputEmail3" placeholder="Email">#} {{ form_obj.name }} {{ form_obj.name.errors }} </div> </div> <div class="form-group"> <label for="{{ form_obj.count.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.count.label }}</label> <div class="col-sm-8"> {{ form_obj.count }} {{ form_obj.count.errors }} </div> </div> <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> </form> </div> </div> {% endblock %} 输入框设置表单状态,错误时显示红色错误提示 #通过if 判断和bootstrape实现 {% extends 'layout.html' %} {% block content %} <div class="container"> <div style="margin-top: 20px"> <form class="form-horizontal" method="post" action="" novalidate> {% csrf_token %} <div class="form-group {% if form_obj.name.errors %}has-error{% endif %}"> <label for="{{ form_obj.name.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.name.label }}</label> <div class="col-sm-8"> {{ form_obj.name }} <span class="help-block">{{ form_obj.name.errors.0 }}</span> </div> </div> <div class="form-group"> <label for="{{ form_obj.count.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.count.label }}</label> <div class="col-sm-8"> {# <input type="email" class="form-control" id="inputEmail3" placeholder="Email">#} {{ form_obj.count }} {{ form_obj.count.errors.0 }} </div> </div> <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> </form> </div> </div> {% endblock %} 设置modelform class DepForm(forms.ModelForm): class Meta: #models 根据某一个模型生成对应的字段 model = models.Department #model命令否则会报错 fields = '__all__' #拿所有的字段 fields = ['name'] 拿想拿的字段 #exclude = ['count'] 排除不想要的字段 # labels = { # 'name':'名称' #设置提示 # } widgets = { 'name':forms.TextInput(attrs={'class':'form-control'}) #设置样式 } error_messages = { 'name':{'required':'此项是必填的'} #设置错误提示信息 }
通过for循环生成多个输入框
{% extends 'layout.html' %} {% block content %} <div class="container"> <div style="margin-top: 20px"> <form class="form-horizontal" method="post" action="" novalidate> {% csrf_token %} {% for field in form_obj %} <div class="form-group {% if form_obj.name.errors %}has-error{% endif %}"> <label for="{{ field.id_for_label }}" class="col-sm-2 control-label">{{ field.label }}</label> <div class="col-sm-8"> {{ field }} <span class="help-block">{{ field.errors.0 }}</span> </div> </div> {% endfor %} <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> </form> </div> </div> {% endblock %}
通过init方法统一设置样式
class DepForm(forms.ModelForm): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) #初始化父类方法 print(self.fields) for field in self.fields.values(): field.widget.attrs = {'class':'form-control'} class Meta: #models 根据某一个模型生成对应的字段 model = models.Department #model命令否则会报错 fields = '__all__' #拿所有的字段 fields = ['name'] 拿想拿的字段 def department_add(request): form_obj = DepForm() if request.method == 'POST': form_obj = DepForm(request.POST) if form_obj.is_valid(): """ 数据校验成功 """ print(form_obj.cleaned_data) # models.Department.objects.create(name=form_obj.cleaned_data.get('name'),count=form_obj.cleaned_data['count']) #models.Department.objects.create(**form_obj.cleaned_data)
form_obj.save() #直接把数据插入数据库里面 return redirect("/department_list/") return render(request,'department_add.html',{'form_obj':form_obj})
查询案例
后台代码 def department_list(request): all_depart = models.Department.objects.all() return render(request,'department_list.html',{'all_depart':all_depart}) 模板代码 {% extends 'layout.html' %} {% block content %} <div class="container" style="margin-top: 10px"> <table class="table table-bordered"> <thead> <tr> <th>序号</th> <th>名称</th> <th>人数</th> <th>操作</th> </tr> </thead> <tbody> {% for depart in all_depart %} <tr> <td>{{ forloop.counter }}</td> <td>{{ depart.name }}</td> <td>{{ depart.count }}</td> <td> <a href="{% url 'department_edit' depart.pk %}"><i class="fa fa-edit"></i> </a> <a href="{% url 'department_del' depart.pk %}"><i class="fa fa-trash-o"></i></a> </td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %}
添加案例
后端代码 def department_add(request): form_obj = DepForm() if request.method == 'POST': form_obj = DepForm(request.POST) if form_obj.is_valid(): """ 数据校验成功 """ print(form_obj.cleaned_data) # models.Department.objects.create(name=form_obj.cleaned_data.get('name'),count=form_obj.cleaned_data['count']) models.Department.objects.create(**form_obj.cleaned_data) return redirect("/department_list/") return render(request,'department_add.html',{'form_obj':form_obj}) 模板代码 {% extends 'layout.html' %} {% block content %} <div class="container"> <div style="margin-top: 20px"> <form class="form-horizontal" method="post" action="" novalidate> {% csrf_token %} {% for field in form_obj %} <div class="form-group {% if form_obj.name.errors %}has-error{% endif %}"> <label for="{{ field.id_for_label }}" class="col-sm-2 control-label">{{ field.label }}</label> <div class="col-sm-8"> {{ field }} <span class="help-block">{{ field.errors.0 }}</span> </div> </div> {% endfor %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">提交</button> </div> </div> </form> </div> </div> {% endblock %}
编辑案例
后端代码 def department_edit(request,pk): obj = models.Department.objects.filter(pk=pk).first() form_obj = DepForm(instance=obj) if request.method == 'POST': form_obj = DepForm(request.POST,instance=obj) #包含原始数据和新数据 if form_obj.is_valid(): form_obj.save() return redirect('/department_list/') return render(request, 'department_edit.html', {'form_obj': form_obj}) 模板代码 {% extends 'layout.html' %} {% block content %} <div class="container"> <div style="margin-top: 20px"> <form class="form-horizontal" method="post" action="" novalidate> {% csrf_token %} {% for field in form_obj %} <div class="form-group {% if form_obj.name.errors %}has-error{% endif %}"> <label for="{{ field.id_for_label }}" class="col-sm-2 control-label">{{ field.label }}</label> <div class="col-sm-8"> {{ field }} <span class="help-block">{{ field.errors.0 }}</span> </div> </div> {% endfor %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">提交</button> </div> </div> </form> </div> </div> {% endblock %}
简单删除案例
def department_del(request,pk): obj = models.Department.objects.filter(pk=pk).first().delete() #根据pk找到对象 return redirect('department_list')
通过ajax和sweetalert删除数据案例
https://sweetalert.js.org/guides/
后端代码 from django.http.response import JsonResponse def department_del(request,pk): ret = {'status':0,'msg':'删除成功'} obj = models.Department.objects.filter(pk=pk).first().delete() #根据pk找到对象 # return redirect('department_list') print(pk) return JsonResponse(ret) 模板文件代码 {% extends 'layout.html' %} {% load static %} {% block content %} <div class="container" style="margin-top: 10px"> {% csrf_token %} <table class="table table-bordered"> <thead> <tr> <th>序号</th> <th>名称</th> <th>人数</th> <th>操作</th> </tr> </thead> <tbody> {% for depart in all_depart %} <tr> <td>{{ forloop.counter }}</td> <td>{{ depart.name }}</td> <td>{{ depart.count }}</td> <td> <a href="{% url 'department_edit' depart.pk %}"><i class="fa fa-edit"></i> </a> <a href=""><i url="{% url 'department_del' depart.pk %}" class="fa fa-trash-o"></i></a> </td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %} {% block js %} <script> $('.fa-trash-o').click(function () { swal({ title: "Are you sure?", text: "Once deleted, you will not be able to recover this imaginary file!", icon: "warning", buttons: true, dangerMode: true, }) .then((willDelete) => { if (willDelete) { $.ajax({ url: $(this).attr('url'), type: 'post', headers: { 'x-csrftoken': $('input[name="csrfmiddlewaretoken"]').val(), }, success: (ret) => { if (!ret.status) { $(this).parent().parent().parent().remove(); swal("Poof! Your imaginary file has been deleted!", { icon: "success", }); } } }); } else { swal("Your imaginary file is safe!"); } }); }) </script> {% endblock %}
ps:测试的过程中有点小瑕疵,但是功能基本上都能实现.
We are down, but not beaten. tested but not defeated.