使用django-dynamic-formset与CreateWithInlinesView从django-extra-views - 多个formets [英] Using django-dynamic-formset with CreateWithInlinesView from django-extra-views - multiple formsets

查看:227
本文介绍了使用django-dynamic-formset与CreateWithInlinesView从django-extra-views - 多个formets的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

一个表单和两个内联表单:

one form and two inline formsets:

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 with django-extra-views

I just started using ClassBasedViews and cant figure out how to use django-dynamic-formset js with django-extra-views in my template.

推荐答案

哦,我的头我想出来:

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

如果您看到任何错误,请指向我。还要感谢任何更好的想法。

If you see any errors please point them to me. Also appreciate any better ideas.

对于那些想使用它的人 - 是的,它应该与任意数量的表单一起使用

For those who want to use this - Yes it should work with any number of formsets

这篇关于使用django-dynamic-formset与CreateWithInlinesView从django-extra-views - 多个formets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆