modelform:

上篇博客中用form组件简单写了一个注册功能,当然,django是很强大的,接下来我们使用升级版的model form组件,来重新看一下注册


from django.forms import ModelForm   #首先当然是要先导入modelform

form:

exclude = ['不想校验的字段']

也是可以写钩子的,需要的话,直接在下面添加就可以了

HTML:

html的ajax部分:

 

 我们一定要注意的一个问题就是后端的字段名跟前端的一定要一一对应,否则会报错,已经踩过坑

 总结逻辑代码,以后使用到都是类似的:

添加书籍:
                def add(reqeust):
                     if GET请求:
                          form=BookModelForm()
                          return render(reqeust,{"form":form})
                          '''
                          渲染页面
                              <form action="" method="post" novalidate>
                                    {% csrf_token %}
                                      {% for field in form %}
                                            <div class="form-group">
                                                 <label for="title">{{ field.label }}</label>
                                                 {{ field }}
                                                 <span>{{ field.errors.0 }}</span>
                                            </div>
                                     {% endfor %}
                                    <input type="submit" value="提交" class="btn btn-default pull-right">
                              </form>
                          '''
                    else POST请求:
                          form=BookModelForm(request.POST)
                          if form.is_valid():
                              form.save() # Book.objects.create(clean_data)
                              return redirect("/")
                          else:
                             return render(reqeust,{"form":form})
                               
                                
                
            编辑书籍: 
                           
                def edit(request,id):
                        edit_obj=Book.objects.get(pk=id)
                        if GET请求:
                          form=BookModelForm(instance=edit_obj)
                          return render(reqeust,{"form":form})
                          '''
                          渲染页面同添加页面
                              
                          '''
                    else POST请求:
                          form=BookModelForm(request.POST,instance=edit_obj)
                          if form.is_valid():
                              form.save() #  edit_obj.update(clean_data)
                              return redirect("/")
                          else:
                             return render(reqeust,{"form":form})
View Code

 

modelformset:

上面我们用到的modelform来渲染form是非常方便的了,但是会有一个问题,modelform尽管功能很轻大了,但是只能渲染一个form,如果我们要批量处理数据还是有些麻烦,所以Django也给我们提供了一个叫做modelformset的组件,下面我们来看一下modelformset是如何使用的

1,首先要有一个modelform:

class StudentStudyRecordModelForm(forms.ModelForm):
    class Meta:
        model=StudentStudyRecord
        fields=["score","homework_note"]
modelform

2,然后引入组件

from django.forms.models import modelformset_factory

3,views视图部分

from django.forms.models import modelformset_factory


class StudentStudyRecordModelForm(forms.ModelForm):
    class Meta:
        model=StudentStudyRecord
        fields=["score","homework_note"]

class RecordScoreView(View):

    def get(self, request,class_study_record_id):

        # 调用modelformset_factory方法,传参model=要用的表,form=自己写的modelform,extra=可以有几个需要添加的,这个地方没有,所以我们写0
        model_formset_cls=modelformset_factory(model=StudentStudyRecord,form=StudentStudyRecordModelForm,extra=0)
        queryset = StudentStudyRecord.objects.filter(classstudyrecord=class_study_record_id)
        formset = model_formset_cls(queryset=queryset)
        return render(request,"student/record_score.html",locals())

    def post(self, request,class_study_record_id):
        model_formset_cls = modelformset_factory(model=StudentStudyRecord, form=StudentStudyRecordModelForm, extra=0)
        queryset = StudentStudyRecord.objects.filter(classstudyrecord=class_study_record_id)
        print("request.POST",request.POST)
        formset=model_formset_cls(request.POST)
        if formset.is_valid():
            formset.save()

        return redirect(request.path)
View Code

4,前端部分

前端页面在form中除了csrf_token之外还必须写上{{ formset.management_form }}

<div class="panel panel-default">
        <div class="panel-heading">学习记录</div>
        <div class="panel-body">
            <div style="width: 680px;margin: 0 auto;">
                <form method="post" action="">
                    {% csrf_token %}
                    {{ formset.management_form }}

                    <table class="table table-bordered">
                        <thead>
                        <tr>
                            <th>姓名</th>
                            <th>考勤</th>
                            <th>作业成绩</th>
                            <th>作业评语</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for form in formset %}
                            <tr>
                                {{ form.id }}
                                <td>{{ form.instance.student }}</td>
                                <td>{{ form.instance.get_record_display }} </td>
                                <td>{{ form.score }} </td>
                                <td>{{ form.homework_note }}</td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                    <input type="submit" value="保存">
                </form>
            </div>
        </div>
    </div>
<hr>
View Code

5,url

re_path('record_score/(\d+)/', views.RecordScoreView.as_view(), name="record_score"),

 效果: