码迷,mamicode.com
首页 > 其他好文 > 详细

Django form表单修改数据

时间:2016-05-31 23:54:09      阅读:540      评论:0      收藏:0      [点我收藏+]

标签:

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 %}

Django form表单修改数据

标签:

原文地址:http://www.cnblogs.com/stefan-liu/p/5547936.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!