使用django-dynamic-formset和来自django-extra-views的CreateWithInlinesView - 多个表单集

时间:2014-04-16 13:28:45

标签: jquery python django django-class-based-views inline-formset

我有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

1 个答案:

答案 0 :(得分:4)

哦,我的头......我想通了:

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

如果您发现任何错误,请将它们指向我。也欣赏任何更好的想法。

对于那些想要使用它的人 - 是的,它应该适用于任意数量的表单集