传统方法(基于方法的视图):http://stellarchariot.com/blog/2011/02/dynamically-add-form-to-formset-using-javascript-and-django/

概要:

服务器端,使用了formset  , 文档在这里:https://docs.djangoproject.com/en/dev/topics/forms/formsets/

客户端,使用脚本动态添加内容。

class based view ,参考这里:http://kevindias.com/writing/django-class-based-views-multiple-inline-formsets/

总结:

重写了get/post方法。

要点:

1. form里面做关联:

# forms.py
from django.forms import ModelForm
from django.forms.models import inlineformset_factory from .models import Recipe, Ingredient, Instruction class RecipeForm(ModelForm):
class Meta:
model = Recipe IngredientFormSet = inlineformset_factory(Recipe, Ingredient)
InstructionFormSet = inlineformset_factory(Recipe, Instruction)

  2. 重写post/get方法,并在里面对子表初始化,注意get里面构造时无参,post里有参。

ingredient_form = IngredientFormSet()  vs  ingredient_form = IngredientFormSet(self.request.POST)

class RecipeCreateView(CreateView):
template_name = 'recipe_add.html'
model = Recipe
form_class = RecipeForm
success_url = 'success/' def get(self, request, *args, **kwargs):
"""
Handles GET requests and instantiates blank versions of the form
and its inline formsets.
"""
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
ingredient_form = IngredientFormSet()
instruction_form = InstructionFormSet()
return self.render_to_response(
self.get_context_data(form=form,
ingredient_form=ingredient_form,
instruction_form=instruction_form)) def post(self, request, *args, **kwargs):
"""
Handles POST requests, instantiating a form instance and its inline
formsets with the passed POST variables and then checking them for
validity.
"""
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
ingredient_form = IngredientFormSet(self.request.POST)
instruction_form = InstructionFormSet(self.request.POST)
if (form.is_valid() and ingredient_form.is_valid() and
instruction_form.is_valid()):
return self.form_valid(form, ingredient_form, instruction_form)
else:
return self.form_invalid(form, ingredient_form, instruction_form)

  3. 保存时做关联:

ingredient_form.instance = self.object
   def form_valid(self, form, ingredient_form, instruction_form):
"""
Called if all forms are valid. Creates a Recipe instance along with
associated Ingredients and Instructions and then redirects to a
success page.
"""
self.object = form.save()
ingredient_form.instance = self.object
ingredient_form.save()
instruction_form.instance = self.object
instruction_form.save()
return HttpResponseRedirect(self.get_success_url())

  4. 模板注意包含两个隐藏域:

                {{ ingredient_form.management_form }}
{{ ingredient_form.non_form_errors }}

  

 3. 自己写了个demo,完整代码看这里: https://github.com/TommyU/dynamic_form/

django 添加动态表格的方法的更多相关文章

  1. 在<s:iterator>标签里给动态表格添加序号

    在<s:iterator>标签里给动态表格添加序号,需要用到<s:iterator>标签里的Status属性里的count eg:<s:iterator value=&q ...

  2. iOS中动态注入JavaScript方法。动态给html标签添加事件

    项目中有这样一种需求,给html5网页中图片添加点击事件,并且弹出弹出点击的对应的图片,并且可以保持图片到本地 应对这样的需求你可能会想到很多方法来实现. 1. 最简单的方法就是在html5中添加图片 ...

  3. QT中添加 动态库(.so) 和 静态库 (.a) 的方法

    在QT 的Makefile文件中: 1 添加动态库,如lipcap.so 则,在LIBS一行中添加“-L/usr/local/lib -lpcap”,依据自己的情况修改libpcap.so的路径 2 ...

  4. excel表格中添加单引号的方法

    今天碰到需要插入大量数据的excel表格,其中有很多文本,需要添加单引号. 方法如下: 左边是原始数据,右边是我即将添加单引号的空白区域. 第一步:在需要添加的位置输入= 第二步:输入等号之后点击需要 ...

  5. python装饰器、继承、元类、mixin,四种給类动态添加类属性和方法的方式(一)

    介绍装饰器.继承.元类.mixin,四种給类动态添加类属性和方法的方式 有时候需要給类添加额外的东西,有些东西很频繁,每个类都需要,如果不想反复的复制粘贴到每个类,可以动态添加. # coding=u ...

  6. js动态给table添加/删除tr的方法

    js动态给table添加/删除tr的方法. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> ...

  7. Celery 分布式任务队列快速入门 以及在Django中动态添加定时任务

    Celery 分布式任务队列快速入门 以及在Django中动态添加定时任务 转自 金角大王 http://www.cnblogs.com/alex3714/articles/6351797.html ...

  8. C#后台动态添加Grid表格

    前面页面: <ScrollViewer x:Name=" BorderBrush="#25A0DA" VerticalScrollBarVisibility=&qu ...

  9. django在style的样式image url添加静态图片路径和django如何动态传入图片链接?

    #django在style的样式image url添加静态图片路径 style=" background:url({% static "agribusiness/images/lo ...

随机推荐

  1. ListView 里面嵌套 GridView 遇到的问题及其解决方法。

    我们直接入主题.所有问题例子请参照下图 1,怎样使图片具有点击事件? 答: 解决方法: 在你的BaseAdapter里面不要设置下面这三个东西,然后再设置GridView的onItemClick. g ...

  2. pulltorefresh滚动到底部

    如果用ListView,让它滚动到顶部,一般是这样写的: if (!listView.isStackFromBottom()) { listView.setStackFromBottom(true); ...

  3. codeforces 712B. Memory and Trident

    题目链接:http://codeforces.com/problemset/problem/712/B 题目大意: 给出一个字符串(由'U''D''L''R'),分别是向上.向下.向左.向右一个单位, ...

  4. PetaPoco 使用总结(一)

    PetaPoco 使用总结(一) 前段时间,公司的一个项目希望用一个ORM 的框架,通过对比 Dapper 和 PetaPoco ,虽然Dapper 功能很强大,速度更快. 但是最终还是选择了比较简单 ...

  5. Robot Framework--01 创建简单工程示例

    1.新建Project: 填写name,选择Type为Dirctory,路径根据自己需要选择,建议最好不要在中文路径下,以免发生问题:

  6. Java并发编程核心方法与框架-Executors的使用

    合理利用线程池能够带来三个好处 降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗. 提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行. 提高线程的可管理性.线程是稀 ...

  7. ASO优化总结(基于网络分享的知识总结归纳)

    如何优化应用标题? 注意关键字的长度,尽量保证每一个关键字小于10个字符.保持快速更新,因为每次更新,你都将有机会删除表现不佳的关键字以 及增添新的关键字.在ASO中使用关键字的正确做法 标题,并非越 ...

  8. CentOS的SSH,Putty配置说明

    基本资源: CentOS5.5 (32位) , Mysql6.0 ,Putty ,SSH   Step: 1.VMWare中装好CentOS    A. 可能存在ifconfig等命令无法正常识别) ...

  9. An error I have completed recently

    在上学期开发javaweb的项目中,遇见一个字符串池的问题. 大致如下: 在上传一篇文章的时候,通过字符串的截取获取该篇文章的后缀名,如doc.pdf.txt....然后规定只能上传pdf和doc格式 ...

  10. MVC中下拉列表绑定方法

    方法一: 前端 @Html.DropDownListFor(a=>a.acate,ViewBag.CateList as IEnumerable<SelectListItem>) 后 ...