我有3个型号:
class Client(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=40) class Phone(models.Model): number = models.CharField(max_length=10) client = models.ForeignKey(Client) class ClientEmail(models.Model): client = models.ForeignKey(Client) address = models.EmailField(verbose_name='Email')
一个表单和两个内联表单集:
class ClientForm(ModelForm): class Meta: model = Client class PhoneFormSet(InlineFormSet): model = Phone extra = 1 class EmailFormSet(InlineFormSet): model = ClientEmail extra = 1
视图:
class ClientCreateView(LoginrequiredMixin,CreateWithInlinesView): model = Client inlines = [PhoneFormSet,EmailFormSet,]
和工作模板:
{% extends 'base.html' %} {% block extra_head_script %} <script src="{{ STATIC_URL }}js/jquery.formset.js"></script> {% endblock %} {% block content %} <form action="." method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> {% for formset in inlines %} <div id="{{ formset.prefix }}"> {% for subform in formset.forms %} <table> {{ subform.as_table }} </table> {% endfor %} {{ formset.management_form }} </div> {% endfor %} <input type="submit" value="Add client" class="submit"/> </form> {% endblock %}
我刚开始使用ClassBasedViews,无法弄清楚如何在我的模板中使用django-dynamic-formset js和django-extra-views.
解决方法
我的脑袋……我想通了:
{% block extra_footer_script %} <script type="text/javascript"> $(function() { {% for formset in inlines %} $('div#FormSet{{ formset.prefix }}').formset({ prefix: '{{ formset.prefix }}',formCssClass: 'dynamic-formset{{ forloop.counter }}' }); {% endfor %} }) </script> {% endblock %}
如果您发现任何错误,请将它们指向我.也欣赏任何更好的想法.
对于那些想要使用它的人 – 是的它应该可以使用任意数量的表单集