form:
#!/usr/bin/env python #coding:utf8 from django.forms import Form,ModelForm import models class CourseModelForm(ModelForm): class Meta: model = models.Course exclude = () def __init__(self,*args,**kwargs): super(CourseModelForm,self).__init__(*args,**kwargs) for fieldname in self.base_fields: #循环给所有字段加样式 field = self.base_fields[fieldname] field.widget.attrs.update({‘class‘:‘form-control‘})
后端:
def mod_course(request,customer_id): print("进入修改课程") course_obj = Course.objects.get(id=customer_id) if request.method == ‘POST‘:#使用form做数据修改 form = forms.CourseModelForm(request.POST,instance=course_obj)#获取POST修改后的数据 if form.is_valid():#判断是否满足form条件 form.save() return redirect(‘/course/‘) print("customer_ID===========>",customer_id) print(course_obj) form = forms.CourseModelForm(instance=course_obj) return render(request,‘course_mod.html‘,{‘course_form‘:form})
前端:
{% extends ‘index.html‘ %} {% block head-menu %} <h2 style="margin-left: 5%">Course modified</h2> <form class="form-horizontal" action="" method="post"> {% for field in course_form %} <div class="form-group"> <label class="col-sm-2 control-label">{{ field.label }}</label> <div class="col-sm-10"> {{ field }} </div> </div> {% endfor %} <input style="margin-left: 50%" class="btn btn-primary btn-rg active" type="submit" value="提交"/> </form> {% endblock %}
时间: 2024-10-12 22:20:01