Django之ModelForm
在admin添加数据
python36 manage.py createsuperuser
在 admin写入
admin.site.register(models.类名)
注册model
数据展示: 1. 普通字段 对象.字段名 ——》 数据库的值 2. choices 对象.字段名 ——》 数据库的值 对象.get_字段名_display() ——》 对应显示的值 3. 外键 对象.外键 ——》 关联的对象 __str__ 对象.外键.字段 4. 自定义方法 def show_class(self): return ' , '.join([str(i) for i in self.class_list.all()]) 返回html页面 from django.utils.safestring import mark_safe 颜色展现 def show_status(self): """ ('signed', "已报名"), ('unregistered', "未报名"), ('studying', '学习中'), ('paid_in_full', "学费已交齐") """ color_dict = { 'signed': 'green', 'unregistered': 'red', 'studying': 'pink', 'paid_in_full': '#208ebc', } return mark_safe('<span style="color: white;background-color: {};padding: 3px">{}</span>'.format(color_dict.get(self.status), self.get_status_display())) 在前端显示是{{ 对象.show_status }}
数据展现
给所有字段增加样式
class CustomerForm(forms.ModelForm): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) for field in self.fields.values(): print(field) field.widget.attrs['class']='form-control' #给所有字段增加样式 field.widget.attrs['style']='border-radius: 3px ' # 第二种方法 field.widget.attrs.update({'class':'form-control','style':'border-radius: 3px '}) class Meta: model = models.Customer #关联的表 fields ='__all__' # 所有数据
字段不需要增加样式的:
第一种方式 名字判断 for name,field in self.fields.items(): if name == 'course': continue #退出本次循环
第二种方式 类型判断 from multiselectfield import MultiSelectField 通过类型看到是MultiSelectField if isinstance(field,(MultiSelectFormField,)): continue
html
{% for field in form_obj %} <div class="form-group"> <label for="{{ field.id_for_label }}" class="col-sm-3 control-label">{{ field.label }}</label> <div class="col-sm-7"> {{ field }} {{ field.errors.0 }} </div> </div> {% endfor %}
若想给不必填数据,label字体颜色变浅改成如下
这里面的第一个field都是for 循环的i
<label for="{{ field.id_for_label }}" {% if not field.field.required %} style="color: gray" {% endif %}class="col-sm-3 control-label">{{ field.label }}</label>
增加报错提示框
{% for field in form_obj %} <div class="form-group {% if field.errors %}has-error{% endif %}"> <label for="{{ field.id_for_label }}" {% if not field.field.required %} style="color: gray" {% endif %}class="col-sm-3 control-label">{{ field.label }}</label> <div class="col-sm-7"> {{ field }} <span class="help-block"> {{ field.errors.0 }}</span> </div> </div> {% endfor %}
新增编辑
url下
url(r'^customer_add/', views.customer_change, name='customer_add'), url(r'^customer_edit/(\d+)', views.customer_change, name='customer_edit'),
views下
def customer_change(request,pk=None): obj = models.Customer.objects.filter(pk=pk).first() form_obj = CustomerForm(instance=obj) if request.method=='POST': form_obj = CustomerForm(request.POST,instance=obj) if form_obj.is_valid(): form_obj.save() return redirect('app01:customer') title = '编辑客户' if pk else '新增客户' return render(request,'customer_change.html',{'form_obj':form_obj,'title':title})
templates下
{% extends 'home.html' %} {% block title %} <h1> {{ title }} <small>Optional description</small> </h1> {% endblock %} {% block content %} <div class="panel panel-primary"> <div class="panel-heading"> 添加 </div> <div class="panel-body"> <form class="form-horizontal" action="" method="post" novalidate> {% csrf_token %} {% for field in form_obj %} <div class="form-group {% if field.errors %}has-error{% endif %}"> <label for="{{ field.id_for_label }}" {% if not field.field.required %} style="color: gray" {% endif %}class="col-sm-3 control-label">{{ field.label }}</label> <div class="col-sm-7"> {{ field }} <span class="help-block"> {{ field.errors.0 }}</span> </div> </div> {% endfor %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-8"> <button type="submit" class="btn btn-success pull-right">提交</button> </div> </div> </form> </div> </div> {% endblock %}